MyBatis提供了一種插件(plugin)的功能,雖然叫做插件,但其實(shí)這是攔截器功能。那么攔截器攔截MyBatis中的哪些內(nèi)容呢?
MyBatis 允許你在已映射語(yǔ)句執(zhí)行過(guò)程中的某一點(diǎn)進(jìn)行攔截調(diào)用。默認(rèn)情況下,MyBatis允許使用插件來(lái)攔截的方法調(diào)用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) 攔截執(zhí)行器的方法;
- ParameterHandler (getParameterObject, setParameters) 攔截參數(shù)的處理;
- ResultSetHandler (handleResultSets, handleOutputParameters) 攔截結(jié)果集的處理;
- StatementHandler (prepare, parameterize, batch, update, query) 攔截Sql語(yǔ)法構(gòu)建的處理;
Mybatis采用責(zé)任鏈模式,通過(guò)動(dòng)態(tài)代理組織多個(gè)攔截器(插件),通過(guò)這些攔截器可以改變Mybatis的默認(rèn)行為(諸如SQL重寫之類的),由于插件會(huì)深入到Mybatis的核心,因此在編寫自己的插件前最好了解下它的原理,以便寫出安全高效的插件。
1 攔截器的使用#
1.1 攔截器介紹及配置##
首先我們看下MyBatis攔截器的接口定義:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
比較簡(jiǎn)單,只有3個(gè)方法。MyBatis默認(rèn)沒(méi)有一個(gè)攔截器接口的實(shí)現(xiàn)類,開發(fā)者們可以實(shí)現(xiàn)符合自己需求的攔截器。下面的MyBatis官網(wǎng)的一個(gè)攔截器實(shí)例:
@Intercepts({@Signature(type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
全局xml配置:
<plugins>
<plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin>
</plugins>
這個(gè)攔截器攔截Executor接口的update方法(其實(shí)也就是SqlSession的新增,刪除,修改操作),所有執(zhí)行executor的update方法都會(huì)被該攔截器攔截到。
1.2 源碼分析##
首先從源頭->配置文件開始分析:
- XMLConfigBuilder解析MyBatis全局配置文件的pluginElement私有方法:
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();
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance);
}
}
}
- 具體的解析代碼其實(shí)比較簡(jiǎn)單,就不貼了,主要就是通過(guò)反射實(shí)例化plugin節(jié)點(diǎn)中的interceptor屬性表示的類。然后調(diào)用全局配置類Configuration的addInterceptor方法。
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
- 這個(gè)interceptorChain是Configuration的內(nèi)部屬性,類型為InterceptorChain,也就是一個(gè)攔截器鏈,我們來(lái)看下它的定義:
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
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<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
- 現(xiàn)在我們理解了攔截器配置的解析以及攔截器的歸屬,現(xiàn)在我們回過(guò)頭看下為何攔截器會(huì)攔截這些方法(Executor,ParameterHandler,ResultSetHandler,StatementHandler的部分方法):
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
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);
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);
return statementHandler;
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {
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, autoCommit);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
以上4個(gè)方法都是Configuration的方法。這些方法在MyBatis的一個(gè)操作(新增,刪除,修改,查詢)中都會(huì)被執(zhí)行到,執(zhí)行的先后順序是Executor,ParameterHandler,ResultSetHandler,StatementHandler,其中ParameterHandler和ResultSetHandler的創(chuàng)建是在創(chuàng)建StatementHandler(3個(gè)可用的實(shí)現(xiàn)類CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler)的時(shí)候,其構(gòu)造函數(shù)調(diào)用的這3個(gè)實(shí)現(xiàn)類的構(gòu)造函數(shù)其實(shí)都調(diào)用了父類BaseStatementHandler的構(gòu)造函數(shù))。
這4個(gè)方法實(shí)例化了對(duì)應(yīng)的對(duì)象之后,都會(huì)調(diào)用interceptorChain的pluginAll方法,InterceptorChain的pluginAll剛才已經(jīng)介紹過(guò)了,就是遍歷所有的攔截器,然后調(diào)用各個(gè)攔截器的plugin方法。注意:攔截器的plugin方法的返回值會(huì)直接被賦值給原先的對(duì)象。
由于可以攔截StatementHandler,這個(gè)接口主要處理sql語(yǔ)法的構(gòu)建,因此比如分頁(yè)的功能,可以用攔截器實(shí)現(xiàn),只需要在攔截器的plugin方法中處理StatementHandler接口實(shí)現(xiàn)類中的sql即可,可使用反射實(shí)現(xiàn)。
MyBatis還提供了@Intercepts和 @Signature關(guān)于攔截器的注解。官網(wǎng)的例子就是使用了這2個(gè)注解,還包括了Plugin類的使用:
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
2 代理鏈的生成#
Mybatis支持對(duì)Executor、StatementHandler、ParameterHandler和ResultSetHandler進(jìn)行攔截,也就是說(shuō)會(huì)對(duì)這4種對(duì)象進(jìn)行代理。通過(guò)查看Configuration類的源代碼我們可以看到,每次都對(duì)目標(biāo)對(duì)象進(jìn)行代理鏈的生成。
下面以Executor為例。Mybatis在創(chuàng)建Executor對(duì)象時(shí)會(huì)執(zhí)行下面一行代碼:
executor =(Executor) interceptorChain.pluginAll(executor);
InterceptorChain里保存了所有的攔截器,它在mybatis初始化的時(shí)候創(chuàng)建。上面這句代碼的含義是調(diào)用攔截器鏈里的每個(gè)攔截器依次對(duì)executor進(jìn)行plugin(插入?)代碼如下:
/**
* 每一個(gè)攔截器對(duì)目標(biāo)類都進(jìn)行一次代理
* @param target
* @return 層層代理后的對(duì)象
*/
public Object pluginAll(Object target) {
for(Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
下面以一個(gè)簡(jiǎn)單的例子來(lái)看看這個(gè)plugin方法里到底發(fā)生了什么:
@Intercepts({@Signature(type = Executor.class, method ="update", args = {MappedStatement.class, Object.class})})
public class ExamplePlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
每一個(gè)攔截器都必須實(shí)現(xiàn)上面的三個(gè)方法,其中:
Object intercept(Invocation invocation)是實(shí)現(xiàn)攔截邏輯的地方,內(nèi)部要通過(guò)invocation.proceed()顯式地推進(jìn)責(zé)任鏈前進(jìn),也就是調(diào)用下一個(gè)攔截器攔截目標(biāo)方法。
Object plugin(Object target)就是用當(dāng)前這個(gè)攔截器生成對(duì)目標(biāo)target的代理,實(shí)際是通過(guò)Plugin.wrap(target,this)來(lái)完成的,把目標(biāo)target和攔截器this傳給了包裝函數(shù)。
setProperties(Properties properties)用于設(shè)置額外的參數(shù),參數(shù)配置在攔截器的Properties節(jié)點(diǎn)里。
注解里描述的是指定攔截方法的簽名 [type,method,args] (即對(duì)哪種對(duì)象的哪種方法進(jìn)行攔截),它在攔截前用于決斷。
定義自己的Interceptor最重要的是要實(shí)現(xiàn)plugin方法和intercept方法,在plugin方法中我們可以決定是否要進(jìn)行攔截進(jìn)而決定要返回一個(gè)什么樣的目標(biāo)對(duì)象。而intercept方法就是要進(jìn)行攔截的時(shí)候要執(zhí)行的方法。
對(duì)于plugin方法而言,其實(shí)Mybatis已經(jīng)為我們提供了一個(gè)實(shí)現(xiàn)。Mybatis中有一個(gè)叫做Plugin的類,里面有一個(gè)靜態(tài)方法wrap(Object target,Interceptor interceptor),通過(guò)該方法可以決定要返回的對(duì)象是目標(biāo)對(duì)象還是對(duì)應(yīng)的代理。這里我們先來(lái)看一下Plugin的源碼:
package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.reflection.ExceptionUtil;
// 這個(gè)類是Mybatis攔截器的核心,大家可以看到該類繼承了InvocationHandler
// 又是JDK動(dòng)態(tài)代理機(jī)制
public class Plugin implements InvocationHandler {
//目標(biāo)對(duì)象
private Object target;
//攔截器
private Interceptor interceptor;
//記錄需要被攔截的類與方法
private Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
//一個(gè)靜態(tài)方法,對(duì)一個(gè)目標(biāo)對(duì)象進(jìn)行包裝,生成代理類。
public static Object wrap(Object target, Interceptor interceptor) {
//首先根據(jù)interceptor上面定義的注解 獲取需要攔截的信息
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
//目標(biāo)對(duì)象的Class
Class<?> type = target.getClass();
//返回需要攔截的接口信息
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
//如果長(zhǎng)度為>0 則返回代理類 否則不做處理
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
//代理對(duì)象每次調(diào)用的方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//通過(guò)method參數(shù)定義的類 去signatureMap當(dāng)中查詢需要攔截的方法集合
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
//判斷是否需要攔截
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
//不攔截 直接通過(guò)目標(biāo)對(duì)象調(diào)用方法
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
//根據(jù)攔截器接口(Interceptor)實(shí)現(xiàn)類上面的注解獲取相關(guān)信息
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
//獲取注解信息
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
//為空則拋出異常
if (interceptsAnnotation == null) { // issue #251
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
//獲得Signature注解信息
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
//循環(huán)注解信息
for (Signature sig : sigs) {
//根據(jù)Signature注解定義的type信息去signatureMap當(dāng)中查詢需要攔截方法的集合
Set<Method> methods = signatureMap.get(sig.type());
//第一次肯定為null 就創(chuàng)建一個(gè)并放入signatureMap
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
//找到sig.type當(dāng)中定義的方法 并加入到集合
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
//根據(jù)對(duì)象類型與signatureMap獲取接口信息
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
//循環(huán)type類型的接口信息 如果該類型存在與signatureMap當(dāng)中則加入到set當(dāng)中去
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
//轉(zhuǎn)換為數(shù)組返回
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
}
下面是倆個(gè)注解類的定義源碼:
package org.apache.ibatis.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
Signature[] value();
}
package org.apache.ibatis.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Signature {
Class<?> type();
String method();
Class<?>[] args();
}
3 Plugin.wrap方法#
從前面可以看出,每個(gè)攔截器的plugin方法是通過(guò)調(diào)用Plugin.wrap方法來(lái)實(shí)現(xiàn)的。代碼如下:
public static Object wrap(Object target, Interceptor interceptor) {
// 從攔截器的注解中獲取攔截的類名和方法信息
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
// 解析被攔截對(duì)象的所有接口(注意是接口)
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if(interfaces.length > 0) {
// 生成代理對(duì)象, Plugin對(duì)象為該代理對(duì)象的InvocationHandler (InvocationHandler屬于java代理的一個(gè)重要概念,不熟悉的請(qǐng)參考相關(guān)概念)
return Proxy.newProxyInstance(type.getClassLoader(), interfaces, new Plugin(target,interceptor,signatureMap));
}
return target;
}
這個(gè)Plugin類有三個(gè)屬性:
private Object target;// 被代理的目標(biāo)類
private Interceptor interceptor;// 對(duì)應(yīng)的攔截器
private Map<Class<?>, Set<Method>> signatureMap;// 攔截器攔截的方法緩存
getSignatureMap方法:
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
if (interceptsAnnotation == null) { // issue #251
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
getSignatureMap方法解釋:首先會(huì)拿到攔截器這個(gè)類的 @Interceptors注解,然后拿到這個(gè)注解的屬性 @Signature注解集合,然后遍歷這個(gè)集合,遍歷的時(shí)候拿出 @Signature注解的type屬性(Class類型),然后根據(jù)這個(gè)type得到帶有method屬性和args屬性的Method。由于 @Interceptors注解的 @Signature屬性是一個(gè)屬性,所以最終會(huì)返回一個(gè)以type為key,value為Set<Method>的Map。
@Intercepts({@Signature(type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
比如這個(gè)@Interceptors注解會(huì)返回一個(gè)key為Executor,value為集合(這個(gè)集合只有一個(gè)元素,也就是Method實(shí)例,這個(gè)Method實(shí)例就是Executor接口的update方法,且這個(gè)方法帶有MappedStatement和Object類型的參數(shù))。這個(gè)Method實(shí)例是根據(jù) @Signature的method和args屬性得到的。如果args參數(shù)跟type類型的method方法對(duì)應(yīng)不上,那么將會(huì)拋出異常。
getAllInterfaces方法:
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
getAllInterfaces方法解釋:根據(jù)目標(biāo)實(shí)例target(這個(gè)target就是之前所說(shuō)的MyBatis攔截器可以攔截的類,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父類們,返回signatureMap中含有target實(shí)現(xiàn)的接口數(shù)組。
所以Plugin這個(gè)類的作用就是根據(jù) @Interceptors注解,得到這個(gè)注解的屬性 @Signature數(shù)組,然后根據(jù)每個(gè) @Signature注解的type,method,args屬性使用反射找到對(duì)應(yīng)的Method。最終根據(jù)調(diào)用的target對(duì)象實(shí)現(xiàn)的接口決定是否返回一個(gè)代理對(duì)象替代原先的target對(duì)象。
我們?cè)俅谓Y(jié)合(Executor)interceptorChain.pluginAll(executor)這個(gè)語(yǔ)句來(lái)看,這個(gè)語(yǔ)句內(nèi)部對(duì)executor執(zhí)行了多次plugin,第一次plugin后通過(guò)Plugin.wrap方法生成了第一個(gè)代理類,姑且就叫executorProxy1,這個(gè)代理類的target屬性是該executor對(duì)象。第二次plugin后通過(guò)Plugin.wrap方法生成了第二個(gè)代理類,姑且叫executorProxy2,這個(gè)代理類的target屬性是executorProxy1...這樣通過(guò)每個(gè)代理類的target屬性就構(gòu)成了一個(gè)代理鏈(從最后一個(gè)executorProxyN往前查找,通過(guò)target屬性可以找到最原始的executor類)。
4 代理鏈上的攔截#
代理鏈生成后,對(duì)原始目標(biāo)的方法調(diào)用都轉(zhuǎn)移到代理者的invoke方法上來(lái)了。Plugin作為InvocationHandler的實(shí)現(xiàn)類,他的invoke方法是怎么樣的呢?
比如MyBatis官網(wǎng)的例子,當(dāng)Configuration調(diào)用newExecutor方法的時(shí)候,由于Executor接口的update(MappedStatement ms, Object parameter)方法被攔截器被截獲。因此最終返回的是一個(gè)代理類Plugin,而不是Executor。這樣調(diào)用方法的時(shí)候,如果是個(gè)代理類,那么會(huì)執(zhí)行:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> 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);
}
}
沒(méi)錯(cuò),如果找到對(duì)應(yīng)的方法被代理之后,那么會(huì)執(zhí)行Interceptor接口的interceptor方法。
在invoke里,如果方法簽名和攔截器中的簽名一致,就調(diào)用攔截器的攔截方法。我們看到傳遞給攔截器的是一個(gè)Invocation對(duì)象,這個(gè)對(duì)象是什么樣子的,他的功能又是什么呢?
public class Invocation {
private Object target;
private Method method;
private Object[] args;
public Invocation(Object target, Method method, Object[] args) {
this.target =target;
this.method =method;
this.args =args;
}
...
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}
可以看到,Invocation類保存了代理對(duì)象的目標(biāo)類,執(zhí)行的目標(biāo)類方法以及傳遞給它的參數(shù)。
在每個(gè)攔截器的intercept方法內(nèi),最后一個(gè)語(yǔ)句一定是return invocation.proceed()(不這么做的話攔截器鏈就斷了,你的mybatis基本上就不能正常工作了)。invocation.proceed()只是簡(jiǎn)單的調(diào)用了下target的對(duì)應(yīng)方法,如果target還是個(gè)代理,就又回到了上面的Plugin.invoke方法了。這樣就形成了攔截器的調(diào)用鏈推進(jìn)。
public Object intercept(Invocation invocation) throws Throwable {
//完成代理類本身的邏輯
...
//通過(guò)invocation.proceed()方法完成調(diào)用鏈的推進(jìn)
return invocation.proceed();
}
5 總結(jié)#
MyBatis攔截器接口提供的3個(gè)方法中:
- plugin方法:用于某些處理器(Handler)的構(gòu)建過(guò)程;
- interceptor方法:用于處理代理類的執(zhí)行;
- setProperties方法:用于攔截器屬性的設(shè)置;
其實(shí)MyBatis官網(wǎng)提供的使用 @Interceptors和 @Signature注解以及Plugin類這樣處理攔截器的方法,我們不一定要直接這樣使用。我們也可以拋棄這3個(gè)類,直接在plugin方法內(nèi)部根據(jù)target實(shí)例的類型做相應(yīng)的操作。
總體來(lái)說(shuō)MyBatis攔截器還是很簡(jiǎn)單的,攔截器本身不需要太多的知識(shí)點(diǎn),但是學(xué)習(xí)攔截器需要對(duì)MyBatis中的各個(gè)接口很熟悉,因?yàn)閿r截器涉及到了各個(gè)接口的知識(shí)點(diǎn)。
我們假設(shè)在MyBatis配置了一個(gè)插件,在運(yùn)行時(shí)會(huì)發(fā)生什么?
- 所有可能被攔截的處理類都會(huì)生成一個(gè)代理
- 處理類代理在執(zhí)行對(duì)應(yīng)方法時(shí),判斷要不要執(zhí)行插件中的攔截方法
- 執(zhí)行插接中的攔截方法后,推進(jìn)目標(biāo)的執(zhí)行
如果有N個(gè)插件,就有N個(gè)代理,每個(gè)代理都要執(zhí)行上面的邏輯。這里面的層層代理要多次生成動(dòng)態(tài)代理,是比較影響性能的。雖然能指定插件攔截的位置,但這個(gè)是在執(zhí)行方法時(shí)動(dòng)態(tài)判斷,初始化的時(shí)候就是簡(jiǎn)單的把插件包裝到了所有可以攔截的地方。
因此,在編寫插件時(shí)需注意以下幾個(gè)原則:
- 不編寫不必要的插件;
- 實(shí)現(xiàn)plugin方法時(shí)判斷一下目標(biāo)類型,是本插件要攔截的對(duì)象才執(zhí)行Plugin.wrap方法,否者直接返回目標(biāo)本省,這樣可以減少目標(biāo)被代理的次數(shù);