Mybatis插件原理(代理+責任鏈)

在實際開發過程當中,咱們常用的Mybaits插件就是分頁插件了,經過分頁插件咱們能夠在不用寫count語句和limit的狀況下就能夠獲取分頁後的數據,給咱們開發帶來很大java

的便利。除了分頁,插件使用場景主要還有更新數據庫的通用字段,分庫分表,加解密等的處理。spring

這篇博客主要講Mybatis插件原理,下一篇博客會設計一個Mybatis插件實現的功能就是每當新增數據的時候不用數據庫自增ID而是經過該插件生成雪花ID,做爲每條數據的主鍵。數據庫

1、JDK動態代理+責任鏈設計模式

Mybatis的插件其實就是個攔截器功能。它利用JDK動態代理和責任鏈設計模式的綜合運用。採用責任鏈模式,經過動態代理組織多個攔截器,經過這些攔截器你能夠作一些apache

一、JDK動態代理案例

public class MyProxy { /** * 一個接口 */ public interface HelloService{ void sayHello(); } /** * 目標類實現接口 */ static class HelloServiceImpl implements HelloService{ @Override public void sayHello() { System.out.println("sayHello......"); } } /** * 自定義代理類須要實現InvocationHandler接口 */ static class HWInvocationHandler implements InvocationHandler { /** * 目標對象 */ private Object target; public HWInvocationHandler(Object target){ this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("------插入前置通知代碼-------------"); //執行相應的目標方法 Object rs = method.invoke(target,args); System.out.println("------插入後置處理代碼-------------"); return rs; } public static Object wrap(Object target) { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),new HWInvocationHandler(target)); } } public static void main(String[] args) { HelloService proxyService = (HelloService) HWInvocationHandler.wrap(new HelloServiceImpl()); proxyService.sayHello(); } }

運行結果設計模式

------插入前置通知代碼------------- sayHello...... ------插入後置處理代碼-------------

二、優化

上面代理的功能是實現了,可是有個很明顯的缺陷,就是HWInvocationHandler是動態代理類,也能夠理解成是個工具類,咱們不可能會把業務代碼寫到寫到到invoke方法裏,數組

不符合面向對象的思想,能夠抽象一下處理。能夠設計一個Interceptor接口,須要作什麼攔截處理實現接口就好了。緩存

public interface Interceptor { /** * 具體攔截處理 */ void intercept(); }

intercept() 方法就能夠處理各類前期準備了mybatis

public class LogInterceptor implements Interceptor { @Override public void intercept() { System.out.println("------插入前置通知代碼-------------"); } } public class TransactionInterceptor implements Interceptor { @Override public void intercept() { System.out.println("------插入後置處理代碼-------------"); } }

代理對象也作一下修改app

public class HWInvocationHandler implements InvocationHandler { private Object target; private List<Interceptor> interceptorList = new ArrayList<>(); public TargetProxy(Object target,List<Interceptor> interceptorList) { this.target = target; this.interceptorList = interceptorList; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //處理多個攔截器 for (Interceptor interceptor : interceptorList) { interceptor.intercept(); } return method.invoke(target, args); } public static Object wrap(Object target,List<Interceptor> interceptorList) { HWInvocationHandler targetProxy = new HWInvocationHandler(target, interceptorList); return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),targetProxy); } }

如今能夠根據須要動態的添加攔截器了,在每次執行業務代碼sayHello()以前都會攔截,看起來高級一點,來測試一下框架

public class Test { public static void main(String[] args) { List<Interceptor> interceptorList = new ArrayList<>(); interceptorList.add(new LogInterceptor()); interceptorList.add(new TransactionInterceptor()); HelloService target = new HelloServiceImpl(); Target targetProxy = (Target) TargetProxy.wrap(target,interceptorList); targetProxy.sayHello(); } }

運行結果

------插入前置通知代碼------------- ------插入後置處理代碼------------- sayHello......

三、再優化

上面的動態代理確實能夠把代理類中的業務邏輯抽離出來,可是咱們注意到,只有前置代理,沒法作到先後代理,因此還須要在優化下。因此須要作更一步的抽象,

把攔截對象信息進行封裝,做爲攔截器攔截方法的參數,把攔截目標對象真正的執行方法放到Interceptor中完成,這樣就能夠實現先後攔截,而且還能對攔截

對象的參數等作修改。設計一個Invocation 對象

public class Invocation { /** * 目標對象 */ private Object target; /** * 執行的方法 */ private Method method; /** * 方法的參數 */ private Object[] args; //省略getset public Invocation(Object target, Method method, Object[] args) { this.target = target; this.method = method; this.args = args; } /** * 執行目標對象的方法 */ public Object process() throws Exception{ return method.invoke(target,args); } }

Interceptor攔截接口作修改

public interface Interceptor { /** * 具體攔截處理 */ Object intercept(Invocation invocation) throws Exception; }

Interceptor實現類

public class TransactionInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Exception{ System.out.println("------插入前置通知代碼-------------"); Object result = invocation.process(); System.out.println("------插入後置處理代碼-------------"); return result; } }

Invocation 類就是被代理對象的封裝,也就是要攔截的真正對象。HWInvocationHandler修改以下:

public class HWInvocationHandler implements InvocationHandler { private Object target; private Interceptor interceptor; public TargetProxy(Object target,Interceptor interceptor) { this.target = target; this.interceptor = interceptor; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Invocation invocation = new Invocation(target,method,args); return interceptor.intercept(invocation); } public static Object wrap(Object target,Interceptor interceptor) { HWInvocationHandler targetProxy = new HWInvocationHandler(target, interceptor); return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),targetProxy); } }

測試類

public class Test { public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor transactionInterceptor = new TransactionInterceptor(); HelloService targetProxy = (Target) TargetProxy.wrap(target,transactionInterceptor); targetProxy.sayHello(); } }

運行結果

------插入前置通知代碼------------- sayHello...... ------插入後置處理代碼-------------

四、再再優化

上面這樣就能實現先後攔截,而且攔截器能獲取攔截對象信息。可是測試代碼的這樣調用看着很彆扭,對應目標類來講,只須要了解對他插入了什麼攔截就好。

再修改一下,在攔截器增長一個插入目標類的方法。

public interface Interceptor { /** * 具體攔截處理 */ Object intercept(Invocation invocation) throws Exception; /** * 插入目標類 */ Object plugin(Object target); } public class TransactionInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Exception{ System.out.println("------插入前置通知代碼-------------"); Object result = invocation.process(); System.out.println("------插入後置處理代碼-------------"); return result; } @Override public Object plugin(Object target) { return TargetProxy.wrap(target,this); } }

這樣目標類僅僅須要在執行前,插入須要的攔截器就行了,測試代碼:

public class Test { public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor transactionInterceptor = new TransactionInterceptor(); //把事務攔截器插入到目標類中 target = (HelloService) transactionInterceptor.plugin(target); target.sayHello(); } }

運行結果

------插入前置通知代碼------------- sayHello...... ------插入後置處理代碼-------------

五、多個攔截器如何處理

到這裏就差很少完成了,那咱們再來思考若是要添加多個攔截器呢,怎麼搞?

public class Test { public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor transactionInterceptor = new TransactionInterceptor(); target = (HelloService) transactionInterceptor.plugin(target); LogInterceptor logInterceptor = new LogInterceptor(); target = (HelloService)logInterceptor.plugin(target); target.sayHello(); } }

運行結果

------插入前置通知代碼------------- ------插入前置通知代碼------------- sayHello...... ------插入後置處理代碼------------- ------插入後置處理代碼-------------

六、責任鏈設計模式

其實上面已經實現的沒問題了,只是還差那麼一點點,添加多個攔截器的時候不太美觀,讓咱們再次利用面向對象思想封裝一下。咱們設計一個InterceptorChain 攔截器鏈類

public class InterceptorChain { private List<Interceptor> interceptorList = new ArrayList<>(); /** * 插入全部攔截器 */ public Object pluginAll(Object target) { for (Interceptor interceptor : interceptorList) { target = interceptor.plugin(target); } return target; } public void addInterceptor(Interceptor interceptor) { interceptorList.add(interceptor); } /** * 返回一個不可修改集合,只能經過addInterceptor方法添加 * 這樣控制權就在本身手裏 */ public List<Interceptor> getInterceptorList() { return Collections.unmodifiableList(interceptorList); } }

其實就是經過pluginAll() 方法包一層把全部的攔截器插入到目標類去而已。測試代碼:

public class Test { public static void main(String[] args) { HelloService target = new HelloServiceImpl(); Interceptor transactionInterceptor = new TransactionInterceptor(); LogInterceptor logInterceptor = new LogInterceptor(); InterceptorChain interceptorChain = new InterceptorChain(); interceptorChain.addInterceptor(transactionInterceptor); interceptorChain.addInterceptor(logInterceptor); target = (Target) interceptorChain.pluginAll(target); target.sayHello(); } }

這裏展現的是JDK動態代理+責任鏈設計模式,那麼Mybatis攔截器就是基於該組合進行開發。

 

2、Mybatis Plugin 插件概念

一、原理

Mybatis的攔截器實現機制跟上面最後優化後的代碼很是的類似。它也有個代理類Plugin(就是上面的HWInvocationHandler)這個類一樣也會實現了InvocationHandler接口,

當咱們調用ParameterHandler,ResultSetHandler,StatementHandler,Executor的對象的時候,,就會執行Plugin的invoke方法,Plugin在invoke方法中根據

@Intercepts的配置信息(方法名,參數等)動態判斷是否須要攔截該方法.再而後使用須要攔截的方法Method封裝成Invocation,並調用Interceptor的proceed方法。

這樣咱們就達到了攔截目標方法的結果。例如Executor的執行大概是這樣的流程:

攔截器代理類對象->攔截器->目標方法 Executor.Method->Plugin.invoke->Interceptor.intercept->Invocation.proceed->method.invoke。

二、如何自定義攔截器?

1) Interceptor接口

首先Mybatis官方早就想到咱們開發會有這樣的需求,因此開放了一個org.apacheibatis.plugin.Interceptor這樣一個接口。這個接口就是和上面Interceptor性質是同樣的

public interface Interceptor { //當plugin函數返回代理,就能夠對其中的方法進行攔截來調用intercept方法 Object intercept(Invocation invocation) throws Throwable; //plugin方法是攔截器用於封裝目標對象的,經過該方法咱們能夠返回目標對象自己,也能夠返回一個它的代理。 Object plugin(Object target); //在Mybatis配置文件中指定一些屬性 void setProperties(Properties properties); }

2)自定義攔截器

這裏的ExamplePlugin和上面的LogInterceptor和TransactionInterceptor性質是同樣的

@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) { } }

3)、全局xml配置

最後若是你使用的是Mybatis.xml也就是Mybatis自己單獨的配置,你能夠須要在這裏配置相應的攔截器名字等。

若是你使用的是spring管理的Mybatis,那麼你須要在Spring配置文件裏面配置註冊相應的攔截器。

這樣一個自定義mybatis插件流程大體就是這樣了。

三、Mybatis四大接口

居然Mybatis是對四大接口進行攔截的,那咱們要先要知道Mybatis的四大接口對象 ExecutorStatementHandleResultSetHandlerParameterHandler

1.Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) MyBatis的執行器,用於執行增刪改查操做; 2.ParameterHandler (getParameterObject, setParameters) 處理SQL的參數對象; 3.ResultSetHandler (handleResultSets, handleOutputParameters) 處理SQL的返回結果集; 4.StatementHandler (prepare, parameterize, batch, update, query) 攔截Sql語法構建的處理

上圖Mybatis框架的整個執行過程。

 

3、Mybatis Plugin 插件源碼

通過上面的分析,再去看Mybastis Plugin 源碼的時候就很輕鬆了。

這幾個也就對應上面的幾個,只不過添加了註解,來判斷是否攔截指定方法。

一、攔截器鏈InterceptorChain

public class InterceptorChain { private final List<Interceptor> interceptors = new ArrayList<Interceptor>(); public Object pluginAll(Object target) { //循環調用每一個Interceptor.plugin方法 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); } }

這個就和咱們上面實現的是同樣的。定義了攔截器鏈

二、Configuration

經過初始化配置文件把全部的攔截器添加到攔截器鏈中。

public class Configuration { protected final InterceptorChain interceptorChain = new InterceptorChain(); //建立參數處理器 public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { //建立ParameterHandler 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) { //建立DefaultResultSetHandler 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) { return newExecutor(transaction, defaultExecutorType); } //產生執行器 public Executor newExecutor(Transaction transaction, ExecutorType executorType) { executorType = executorType == null ? defaultExecutorType : executorType; //這句再作一下保護,囧,防止粗枝大葉的人將defaultExecutorType設成null? executorType = executorType == null ? ExecutorType.SIMPLE : executorType; Executor executor; //而後就是簡單的3個分支,產生3種執行器BatchExecutor/ReuseExecutor/SimpleExecutor 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); } //若是要求緩存,生成另外一種CachingExecutor(默認就是有緩存),裝飾者模式,因此默認都是返回CachingExecutor if (cacheEnabled) { executor = new CachingExecutor(executor); } //此處調用插件,經過插件能夠改變Executor行爲 executor = (Executor) interceptorChain.pluginAll(executor); return executor; } }

從代碼能夠看出Mybatis 在實例化Executor、ParameterHandler、ResultSetHandler、StatementHandler四大接口對象的時候調用interceptorChain.pluginAll()方法插入

進去的。其實就是循環執行攔截器鏈全部的攔截器的plugin() 方法,mybatis官方推薦的plugin方法是Plugin.wrap() 方法,這個類就是咱們上面的TargetProxy類。

三、Plugin

這裏的Plugin就是咱們上面的自定義代理類TargetProxy類

public class Plugin implements InvocationHandler { public static Object wrap(Object target, Interceptor interceptor) { //從攔截器的註解中獲取攔截的類名和方法信息 Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); //取得要改變行爲的類(ParameterHandler|ResultSetHandler|StatementHandler|Executor) Class<?> type = target.getClass(); //取得接口 Class<?>[] interfaces = getAllInterfaces(type, signatureMap); //產生代理,是Interceptor註解的接口的實現類纔會產生代理 if (interfaces.length > 0) { 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<Method> methods = signatureMap.get(method.getDeclaringClass()); //是Interceptor實現類註解的方法纔會攔截處理 if (methods != null && methods.contains(method)) { //調用Interceptor.intercept,也即插入了咱們本身的邏輯 return interceptor.intercept(new Invocation(target, method, args)); } //最後仍是執行原來邏輯 return method.invoke(target, args); } catch (Exception e) { throw ExceptionUtil.unwrapThrowable(e); } } //取得簽名Map,就是獲取Interceptor實現類上面的註解,要攔截的是那個類(Executor,ParameterHandler, ResultSetHandler,StatementHandler)的那個方法 private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) { //取Intercepts註解,例子可參見ExamplePlugin.java Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class); // issue #251 //必須得有Intercepts註解,沒有報錯 if (interceptsAnnotation == null) { throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName()); } //value是數組型,Signature的數組 Signature[] sigs = interceptsAnnotation.value(); //每一個class裏有多個Method須要被攔截,因此這麼定義 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; } //取得接口 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()]); } }

四、Interceptor接口

public interface Interceptor { //攔截 Object intercept(Invocation invocation) throws Throwable; //插入 Object plugin(Object target); //設置屬性(擴展) void setProperties(Properties properties); }

思路 這麼下來思路就很清晰了,咱們經過實現Interceptor類實現自定義攔截器,而後把它放入InterceptorChain(攔截器鏈)中,而後經過JDK動態代理來實現依次攔截處理。

相關文章
相關標籤/搜索