MyBatis之簡單了解Plugin


MyBatis的Configuration配置中有一個Plugin配置,根據其名可以解釋為“插件”,這個插件實質可以理解為“攔截器”。“攔截器”這個名詞不陌生,在眾多框架中均有“攔截器”。這個Plugin有什么用呢?活着說攔截器有什么用呢?可以想想攔截器是怎么實現的。Plugin用到了Java中很重要的一個特性——動態代理。所以這個Plugin可以理解為,在調用一個方法時,我“攔截”其方法做一些我想讓它做的事。它可以攔截以下方法:

在官方文檔中有這么一句話:If you attempt to modify or override the behaviour of a given method, you’re likely to break the core of MyBatis. 謹慎使用自定義Plugin攔截器,因為它可能修改Mybatis核心的東西。實現自定義Plugin我們需要實現 Interceptor接口。並未這個類注解@Intercepts。

 1 package day_8_mybatis.util;
 2 
 3 import java.util.Iterator;
 4 import java.util.Map;
 5 import java.util.Properties;
 6 
 7 import org.apache.ibatis.plugin.Interceptor;
 8 import org.apache.ibatis.plugin.Intercepts;
 9 import org.apache.ibatis.plugin.Invocation;
10 import org.apache.ibatis.plugin.Plugin;
11 import org.apache.ibatis.plugin.Signature;
12 
13 /**
14  * @author turbo
15  *
16  * 2016年10月25日
17  */
18 @Intercepts({
19     @Signature(
20         type = Map.class,
21         method = "get",
22         args = {Object.class}
23 )})
24 public class ExamplePlugin implements Interceptor {
25 
26     /* 此方法用於實現攔截邏輯
27      * @see org.apache.ibatis.plugin.Interceptor#intercept(org.apache.ibatis.plugin.Invocation)
28      */
29     @Override
30     public Object intercept(Invocation invocation) throws Throwable {
31         
32         return "ExamplePlugin";
33     }
34 
35     /* 使用當前的這個攔截器實現對目標對象的代理(內部實現時Java的動態代理)
36      * @see org.apache.ibatis.plugin.Interceptor#plugin(java.lang.Object)
37      */
38     @Override
39     public Object plugin(Object target) {
40         return Plugin.wrap(target, this);
41     }
42 
43     /* 此方法和上一節所講的自定義對象工廠中的setProperties一樣,初始化Configuration時通過配置文件配置property傳遞參數給此方法並調用。
44      * @see org.apache.ibatis.plugin.Interceptor#setProperties(java.util.Properties)
45      */
46     @Override
47     public void setProperties(Properties properties) {  
48         Iterator iterator = properties.keySet().iterator();
49         while (iterator.hasNext()){
50             String keyValue = String.valueOf(iterator.next());
51             System.out.println(properties.getProperty(keyValue));
52         }
53     }
54 
55 }

別忘了在mybatis-config.xml的配置文件中注冊自定義Plugin。(下面的配置中有一些遺留代碼,是在上兩節中的配置,可以選擇性的忽略。)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration  
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5   
 6 <configuration>
 7 <!-- 注意configuration中各個屬性配置的順序應為:properties,settings,typeAliases,typeHandlers,objectFactory,objectWrapperFactory,reflectorFactory,plugins,environments,databaseIdProvider,mappers)-->
 8     <properties>
 9         <property name="driver" value="com.mysql.jdbc.Driver"/>
10         <property name="url" value="jdbc:mysql://localhost:3306/test"/>    
11         <property name="username" value="root"/>
12         <property name="password" value="0000"/>
13     </properties>
14     <!-- 
15     <typeHandlers>
16         <typeHandler handler="day_8_mybatis.util.ExampleTypeHandler" javaType="java.util.Date" jdbcType="VARCHAR"/>
17     </typeHandlers>
18     <objectFactory type="day_8_mybatis.util.ExampleObjectFactory">
19         <property name="someProperty" value="100"/>
20     </objectFactory>
21      -->
22     <plugins>
23         <plugin interceptor="day_8_mybatis.util.ExamplePlugin">
24             <property name="someProperty" value="100"/>
25         </plugin>
26     </plugins>
27     <environments default="development">
28         <environment id="development">
29             <transactionManager type="JDBC" />
30             <dataSource type="POOLED">
31                 <property name="driver" value="${driver}"/>
32                 <property name="url" value="${url}"/>
33                 <property name="username" value="${username}"/>
34                 <property name="password" value="${password}"/>
35             </dataSource>            
36         </environment>
37     </environments> 
38     <mappers>
39         <mapper resource="day_8_mybatis/mapper/UserMapper.xml"/>
40         <mapper resource="day_8_mybatis/mapper/NoteMapper.xml"/>
41     </mappers>    
42     
43 </configuration>
44 
45  

客戶端測試代碼:

 1 package day_8_mybatis;
 2 
 3 import java.io.IOException;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 
 7 import org.apache.ibatis.session.SqlSession;
 8 
 9 import day_8_mybatis.util.ExamplePlugin;
10 import day_8_mybatis.util.SessionFactory;
11 
12 /**
13  * 客戶端
14  * @author turbo
15  *
16  * 2016年10月25日
17  */
18 public class Main {
19 
20     /**
21      * @param args
22      * @throws IOException 
23      */
24     public static void main(String[] args) throws Exception {
25         String resource = "day_8_mybatis/mybatis-config.xml";        //獲取mybatis配置文件路徑
26         SqlSession sqlSession = SessionFactory.getSqlSession(resource);    //通過SessionFactory工具類(此工具類為自己構造即util包中的SessionFactory)構造SqlSession
27         
28         Map map = new HashMap();
29         map = (Map)new ExamplePlugin().plugin(map);
30         System.out.println(map.get(""));
31 
32     }
33 
34 }

至此,我們就簡單的了解了MyBatis中的Plugin。有興趣的可以看看我們在客戶端測試代碼中的第29行所調用的plugin方法。即調用了Plugin類的靜態方法wrap(Object target, Interceptor intercpetor),追蹤該方法會發現,此方法即是Java的動態代理。

 1 public static Object wrap(Object target, Interceptor interceptor)
 2     {
 3         Map signatureMap = getSignatureMap(interceptor);
 4         Class type = target.getClass();
 5         Class interfaces[] = getAllInterfaces(type, signatureMap);
 6         if(interfaces.length > 0)
 7             return Proxy.newProxyInstance(type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap));  //返回代理類實例
 8         else
 9             return target;
10     }

動態代理很重要,反射很重要。一定要反復理解領會動態代理以及反射,這對我們讀懂很多框架源代碼有很大幫助。這篇僅僅簡單了解,不做過多的深入。

 


免責聲明!

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



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