【MyBatis源碼分析】插件實現原理


MyBatis插件原理----從<plugins>解析開始

本文分析一下MyBatis的插件實現原理,在此之前,如果對MyBatis插件不是很熟悉的朋友,可參看此文MyBatis7:MyBatis插件及示例----打印每條SQL語句及其執行時間,本文我以一個例子說明了MyBatis插件是什么以及如何實現。由於MyBatis的插件已經深入到了MyBatis底層代碼,因此要更好地使用插件,必須對插件實現原理及MyBatis底層代碼有所熟悉才行,本文分析一下MyBatis的插件實現原理。

首先,我們從插件<plugins>解析開始,源碼位於XMLConfigBuilder的pluginElement方法中:

 1 private void pluginElement(XNode parent) throws Exception {
 2     if (parent != null) {
 3       for (XNode child : parent.getChildren()) {
 4         String interceptor = child.getStringAttribute("interceptor");
 5         Properties properties = child.getChildrenAsProperties();
 6         Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
 7         interceptorInstance.setProperties(properties);
 8         configuration.addInterceptor(interceptorInstance);
 9       }
10     }
11 }

這里拿<plugin>標簽中的interceptor屬性,這是自定義的攔截器的全路徑,第6行的代碼通過反射生成攔截器實例。

再拿<plugin>標簽下的所有<property>標簽,解析name和value屬性成為一個Properties,將Properties設置到攔截器中。

最后,通過第8行的代碼將攔截器設置到Configuration中,源碼實現為:

 1 public void addInterceptor(Interceptor interceptor) {
 2     interceptorChain.addInterceptor(interceptor);
 3 }

InterceptorChain是一個攔截器鏈,存儲了所有定義的攔截器以及相關的幾個操作的方法:

 1 public class InterceptorChain {
 2 
 3   private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
 4 
 5   public Object pluginAll(Object target) {
 6     for (Interceptor interceptor : interceptors) {
 7       target = interceptor.plugin(target);
 8     }
 9     return target;
10   }
11 
12   public void addInterceptor(Interceptor interceptor) {
13     interceptors.add(interceptor);
14   }
15   
16   public List<Interceptor> getInterceptors() {
17     return Collections.unmodifiableList(interceptors);
18   }
19 
20 }

分別有添加攔截器、為目標對象添加所有攔截器、獲取當前所有攔截器三個方法。

 

MyBatis插件原理----pluginAll方法添加插件

上面我們在InterceptorChain中看到了一個pluginAll方法,pluginAll方法為目標對象生成代理,之后目標對象調用方法的時候走的不是原方法而是代理方法,這個在后面會說明。

MyBatis官網文檔有說明,在以下四個代碼執行點上允許使用插件:

 

為之生成插件的時機(換句話說就是pluginAll方法調用的時機)是Executor、ParameterHandler、ResultSetHandler、StatementHandler四個接口實現類生成的時候,每個接口實現類在MyBatis中生成的時機是不一樣的,這個就不看它們是在什么時候生成的了,每個開發工具我相信都有快捷鍵可以看到pluginAll方法調用的地方,我使用的Eclipse就是Ctrl+Alt+H。

再看pluginAll方法:

1 public Object pluginAll(Object target) {
2     for (Interceptor interceptor : interceptors) {
3       target = interceptor.plugin(target);
4     }
5     return target;
6 }

這里值得注意的是:

  1. 形參Object target,這個是Executor、ParameterHandler、ResultSetHandler、StatementHandler接口的實現類,換句話說,plugin方法是要為Executor、ParameterHandler、ResultSetHandler、StatementHandler的實現類生成代理,從而在調用這幾個類的方法的時候,其實調用的是InvocationHandler的invoke方法
  2. 這里的target是通過for循環不斷賦值的,也就是說如果有多個攔截器,那么如果我用P表示代理,生成第一次代理為P(target),生成第二次代理為P(P(target)),生成第三次代理為P(P(P(target))),不斷嵌套下去,這就得到一個重要的結論:<plugins>...</plugins>中后定義的<plugin>實際其攔截器方法先被執行,因為根據這段代碼來看,后定義的<plugin>代理實際后生成,包裝了先生成的代理,自然其代理方法也先執行

plugin方法中調用MyBatis提供的現成的生成代理的方法Plugin.wrap(Object target, Interceptor interceptor),接着我們看下wrap方法的源碼實現。

 

MyBatis插件原理----Plugin的wrap方法的實現

Plugin的wrap方法實現為:

 1 public static Object wrap(Object target, Interceptor interceptor) {
 2     Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
 3     Class<?> type = target.getClass();
 4     Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
 5     if (interfaces.length > 0) {
 6       return Proxy.newProxyInstance(
 7           type.getClassLoader(),
 8           interfaces,
 9           new Plugin(target, interceptor, signatureMap));
10     }
11     return target;
12 }

首先看一下第2行的代碼,獲取Interceptor上定義的所有方法簽名:

 1 private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
 2     Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
 3     // issue #251
 4     if (interceptsAnnotation == null) {
 5       throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
 6     }
 7     Signature[] sigs = interceptsAnnotation.value();
 8     Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
 9     for (Signature sig : sigs) {
10       Set<Method> methods = signatureMap.get(sig.type());
11       if (methods == null) {
12         methods = new HashSet<Method>();
13         signatureMap.put(sig.type(), methods);
14       }
15       try {
16         Method method = sig.type().getMethod(sig.method(), sig.args());
17         methods.add(method);
18       } catch (NoSuchMethodException e) {
19         throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
20       }
21     }
22     return signatureMap;
23 }

看到先拿@Intercepts注解,如果沒有定義@Intercepts注解,拋出異常,這意味着使用MyBatis的插件,必須使用注解方式

接着拿到@Intercepts注解下的所有@Signature注解,獲取其type屬性(表示具體某個接口),再根據method與args兩個屬性去type下找方法簽名一致的方法Method(如果沒有方法簽名一致的就拋出異常,此簽名的方法在該接口下找不到),能找到的話key=type,value=Set<Method>,添加到signatureMap中,構建出一個方法簽名映射。舉個例子來說,就是我定義的@Intercepts注解,Executor下我要攔截的所有Method、StatementHandler下我要攔截的所有Method。

回過頭繼續看wrap方法,在拿到方法簽名映射后,調用getAllInterfaces方法,傳入的是Target的Class對象以及之前獲取到的方法簽名映射:

 1 private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
 2     Set<Class<?>> interfaces = new HashSet<Class<?>>();
 3     while (type != null) {
 4       for (Class<?> c : type.getInterfaces()) {
 5         if (signatureMap.containsKey(c)) {
 6           interfaces.add(c);
 7         }
 8       }
 9       type = type.getSuperclass();
10     }
11     return interfaces.toArray(new Class<?>[interfaces.size()]);
12 }

這里獲取Target的所有接口,如果方法簽名映射中有這個接口,那么添加到interfaces中,這是一個Set,最終將Set轉換為數組返回。

wrap方法的最后一步:

1 if (interfaces.length > 0) {
2   return Proxy.newProxyInstance(
3       type.getClassLoader(),
4       interfaces,
5       new Plugin(target, interceptor, signatureMap));
6 }
7 return target;

如果當前傳入的Target的接口中有@Intercepts注解中定義的接口,那么為之生成代理,否則原Target返回。

這段理論可能大家會看得有點雲里霧里,我這里舉個例子:

就以SqlCostPlugin為例,我的@Intercepts定義的是:
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), @Signature(type = StatementHandler.class, 
method = "update", args = {Statement.class})}) 此時,生成的方法簽名映射signatureMap應當是(我這里把Map給toString()了): {interface org.apache.ibatis.executor.statement.StatementHandler=[public abstract int org.apache.ibatis.executor.statement.StatementHandler.update(java.sql.
Statement) throws java.sql.SQLException, public abstract java.util.List org.apache.ibatis.executor.statement.StatementHandler.query(java.sql.Statement,org.apache.
ibatis.session.ResultHandler) throws java.sql.SQLException]}
一個Class對應一個Set,Class為StatementHandler.class,Set為StataementHandler中的兩個方法

如果我new的是StatementHandler接口的實現類,那么可以為之生成代理,因為signatureMap中的key有StatementHandler這個接口

如果我new的是Executor接口的實現類,那么直接會把Executor接口的實現類原樣返回,因為signatureMap中的key並沒有Executor這個接口

相信這么解釋大家應該會明白一點。注意這里生不生成代理,只和接口在不在@Intercepts中定義過有關,和方法簽名無關,具體某個方法走攔截器,在invoke方法中,馬上來看一下。

 

MyBatis插件原理----Plugin的invoke方法

首先看一下Plugin方法的方法定義:

 1 public class Plugin implements InvocationHandler {
 2 
 3   private Object target;
 4   private Interceptor interceptor;
 5   private Map<Class<?>, Set<Method>> signatureMap;
 6 
 7   private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
 8     this.target = target;
 9     this.interceptor = interceptor;
10     this.signatureMap = signatureMap;
11   }
12   ...
13 }

看到Plugin是InvocationHandler接口的實現類,換句話說,為目標接口生成代理之后,最終執行的都是Plugin的invoke方法,看一下invoke方法的實現:

 1 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 2     try {
 3       Set<Method> methods = signatureMap.get(method.getDeclaringClass());
 4       if (methods != null && methods.contains(method)) {
 5         return interceptor.intercept(new Invocation(target, method, args));
 6       }
 7       return method.invoke(target, args);
 8     } catch (Exception e) {
 9       throw ExceptionUtil.unwrapThrowable(e);
10     }
11 }

在這里,將method對應的Class拿出來,獲取該Class中有哪些方法簽名,換句話說就是Executor、ParameterHandler、ResultSetHandler、StatementHandler,在@Intercepts注解中定義了要攔截哪些方法簽名。

如果當前調用的方法的方法簽名在方法簽名集合中,即滿足第4行的判斷,那么調用攔截器的intercept方法,否則方法原樣調用,不會執行攔截器。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM