所有的框架都支持插件,我們可以用插件編寫來擴(kuò)展我們自己需要的功能,mybatis也不例外。因此,本文將從插件配置、插件編寫、插件運(yùn)行原理,插件注冊(cè)與執(zhí)行時(shí)機(jī)、初始化插件、分頁插件原理來梳理說明。
插件配置
mybatis的分頁插件配置在mybatis的構(gòu)造器configuration,我們?cè)诔跏蓟痬ybatis的時(shí)候就會(huì)獨(dú)去這些插件,并且放到mybatis的攔截鏈InterceptorChain中,如:
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.mybatis3.interceptor.MyBatisInterceptor">
<property name="value" value="100" />
</plugin>
</plugins>
</configuration>
public class Configuration {
protected final InterceptorChain interceptorChain = new InterceptorChain();
}
org.apache.ibatis.plugin.InterceptorChain.java源碼:
public class InterceptorChain {
private final List interceptors = new ArrayList();
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
public List getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
插件編寫
我們自己寫的插件必須要實(shí)現(xiàn)mybatis的org.apache.ibatis.plugin.Interceptor接口:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
intercept()方法:執(zhí)行攔截內(nèi)容的地方,比如想收點(diǎn)保護(hù)費(fèi)。由plugin()方法觸發(fā),interceptor.plugin(target)足以證明。
plugin()方法:決定是否觸發(fā)intercept()方法。
setProperties()方法:給自定義的攔截器傳遞xml配置的屬性參數(shù)。
自定義一個(gè)攔截器:
@Intercepts({
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class }),
@Signature(type = Executor.class, method = "close", args = { boolean.class }) })
public class MyBatisInterceptor implements Interceptor {
private Integer value;
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 從 Invocation 中獲取參數(shù) final Object[] queryArgs = invocation.getArgs();
? ? ? ? final MappedStatement ms = (MappedStatement) queryArgs[MAPPEDSTATEMENT_INDEX];
? ? ? ? final Object parameter = queryArgs[PARAMETER_INDEX];
? ? ? ? //? 獲取分頁參數(shù)? ? ? ? Page paingParam = PageUtil.getPaingParam();
? ? ? ? if (paingParam != null) {
? ? ? ? ? ? // 構(gòu)造新的 sql, select xxx from xxx where yyy limit offset,limit? ? ? ? ? ? final BoundSql boundSql = ms.getBoundSql(parameter);
? ? ? ? ? ? String pagingSql = getPagingSql(boundSql.getSql(), paingParam.getOffset(), paingParam.getLimit());
? ? ? ? ? ? // 設(shè)置新的 MappedStatement? ? ? ? ? ? BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), pagingSql,
? ? ? ? ? ? ? ? ? ? boundSql.getParameterMappings(), boundSql.getParameterObject());
? ? ? ? ? ? MappedStatement mappedStatement = newMappedStatement(ms, newBoundSql);
? ? ? ? ? ? queryArgs[MAPPEDSTATEMENT_INDEX] = mappedStatement;
? ? ? ? ? ? // 重置 RowBound? ? ? ? ? ? queryArgs[ROWBOUNDS_INDEX] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
? ? ? ? }
? ? ? ? Object result = invocation.proceed();
? ? ? ? PageUtil.removePagingParam();
? ? ? ? return result;
}
@Override
public Object plugin(Object target) {
System.out.println(value);
// Plugin類是插件的核心類,用于給target創(chuàng)建一個(gè)JDK的動(dòng)態(tài)代理對(duì)象,觸發(fā)intercept()方法
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
value = Integer.valueOf((String) properties.get("value"));
}
}
注解的作用:
@Intercepts注解:裝載一個(gè)@Signature列表,一個(gè)@Signature其實(shí)就是一個(gè)需要攔截的方法封裝。那么,一個(gè)攔截器要攔截多個(gè)方法,自然就是一個(gè)@Signature列表。
type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }
解釋:要攔截Executor接口內(nèi)的query()方法,參數(shù)類型為args列表。
如何執(zhí)行這個(gè)插件呢?
請(qǐng)看自定義代碼中的Plugin.wrap(target, this),這是用JDK的動(dòng)態(tài)代理機(jī)制來實(shí)現(xiàn)的,以此來實(shí)現(xiàn)方法的攔截和增強(qiáng)功能,執(zhí)行后會(huì)回調(diào)intercept()方法。
org.apache.ibatis.plugin.Plugin.java源碼:
public class Plugin implements InvocationHandler {
private Object target;
private Interceptor interceptor;
private Map, Set> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map, Set> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
public static Object wrap(Object target, Interceptor interceptor) {
Map, Set> signatureMap = getSignatureMap(interceptor);
Class type = target.getClass();
Class[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
// 創(chuàng)建JDK動(dòng)態(tài)代理對(duì)象
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set methods = signatureMap.get(method.getDeclaringClass());
// 判斷是否是需要攔截的方法(很重要)
if (methods != null && methods.contains(method)) {
// 回調(diào)intercept()方法
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
//...
}
Map<Class<?>, Set<Method>> signatureMap:緩存需攔截對(duì)象的反射結(jié)果,避免多次反射,即target的反射結(jié)果。
mybatis可以攔截哪些對(duì)象呢?
請(qǐng)看mybatis的Configuration構(gòu)造類
public class Configuration {
//...
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler); // 1
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler); // 2
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler); // 3
return statementHandler;
}
public Executor newExecutor(Transaction transaction) {
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor); // 4
return executor;
}
//...
}
mybatis只能攔截ParameterHandler、ResultSetHandler、StatementHandler、Executor共4個(gè)接口對(duì)象內(nèi)的方法。
interceptorChain.pluginAll():該方法在創(chuàng)建上述4個(gè)接口對(duì)象時(shí)調(diào)用,其含義為給這些接口對(duì)象注冊(cè)攔截器功能,注意是注冊(cè),而不是執(zhí)行攔截。
攔截器執(zhí)行時(shí)機(jī):plugin()方法注冊(cè)攔截器后,那么,在執(zhí)行上述4個(gè)接口對(duì)象內(nèi)的具體方法時(shí),就會(huì)自動(dòng)觸發(fā)攔截器的執(zhí)行,也就是插件的執(zhí)行。
Invocation
調(diào)用執(zhí)行攔截
public class Invocation {
private Object target;
private Method method;
private Object[] args;
}
org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XNode)方法部分源碼:
pluginElement(root.evalNode("plugins"));
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
// 這里展示了setProperties()方法的調(diào)用時(shí)機(jī)
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance);
}
}
}
可以看到,上面并沒有明確標(biāo)明哪種攔截器,統(tǒng)一獲取的是plugins的配置,即所有攔截器。因此對(duì)于Mybatis,它并不區(qū)分是何種攔截器接口,所有的插件都是Interceptor,Mybatis完全依靠Annotation去標(biāo)識(shí)對(duì)誰進(jìn)行攔截,所以,具備接口一致性。
分頁插件原理
我們通常用mybatis開發(fā),都是手寫sql,通過邏輯進(jìn)行分頁,那么不希望通過邏輯分頁,傳入sql直接分頁,物理強(qiáng)行進(jìn)行分頁可否?這里就用到插件功能了。
要實(shí)現(xiàn)物理分頁,就需要對(duì)String sql進(jìn)行攔截并增強(qiáng),Mybatis通過BoundSql對(duì)象存儲(chǔ)String sql,而BoundSql則由StatementHandler對(duì)象獲取。
public interface StatementHandler {
List query(Statement statement, ResultHandler resultHandler) throws SQLException;
BoundSql getBoundSql();
}
public class BoundSql {
public String getSql() {
return sql;
}
}
因此,就需要編寫一個(gè)針對(duì)StatementHandler的query方法攔截器,然后獲取到sql,對(duì)sql進(jìn)行重寫增強(qiáng)。