Mybatis插件原理
在實際開發過程中,我們經常使用的Mybaits插件就是分頁插件了,通過分頁插件我們可以在不用寫count語句和limit的情況下就可以獲取分頁后的數據,給我們開發帶來很大
的便利。除了分頁,插件使用場景主要還有更新數據庫的通用字段,分庫分表,加解密等的處理。
這篇博客主要講Mybatis插件原理,下一篇博客會設計一個Mybatis插件實現的功能就是每當新增數據的時候不用數據庫自增ID而是通過該插件生成雪花ID,作為每條數據的主鍵。
一、JDK動態代理+責任鏈設計模式
Mybatis的插件其實就是個攔截器功能。它利用JDK動態代理和責任鏈設計模式的綜合運用
。采用責任鏈模式,通過動態代理組織多個攔截器,通過這些攔截器你可以做一些
你想做的事。所以在講Mybatis攔截器之前我們先說說JDK動態代理+責任鏈設計模式。有關JDK動態代理的原理,可以參考我之前寫的一篇博客:【java設計模式】---代理模式
1、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......
------插入后置處理代碼-------------
2、優化
上面代理的功能是實現了,但是有個很明顯的缺陷,就是HWInvocationHandler是動態代理類
,也可以理解成是個工具類,我們不可能會把業務代碼寫到寫到到invoke方法
里,
不符合面向對象的思想,可以抽象一下處理。可以設計一個Interceptor接口
,需要做什么攔截處理實現接口就行了。
public interface Interceptor {
/**
* 具體攔截處理
*/
void intercept();
}
intercept() 方法就可以處理各種前期准備了
public class LogInterceptor implements Interceptor {
@Override
public void intercept() {
System.out.println("------插入前置通知代碼-------------");
}
}
public class TransactionInterceptor implements Interceptor {
@Override
public void intercept() {
System.out.println("------插入后置處理代碼-------------");
}
}
代理對象也做一下修改
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......
3、再優化
上面的動態代理確實可以把代理類中的業務邏輯抽離出來,但是我們注意到,只有前置代理,無法做到前后代理,所以還需要在優化下。所以需要做更一步的抽象,
把攔截對象信息進行封裝,作為攔截器攔截方法的參數,把攔截目標對象真正的執行方法放到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......
------插入后置處理代碼-------------
4、再再優化
上面這樣就能實現前后攔截,並且攔截器能獲取攔截對象信息。但是測試代碼的這樣調用看着很別扭,對應目標類來說,只需要了解對他插入了什么攔截就好。
再修改一下,在攔截器增加一個插入目標類的方法。
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......
------插入后置處理代碼-------------
5、多個攔截器如何處理
到這里就差不多完成了,那我們再來思考如果要添加多個攔截器呢,怎么搞?
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......
------插入后置處理代碼-------------
------插入后置處理代碼-------------
6、責任鏈設計模式
其實上面已經實現的沒問題了,只是還差那么一點點,添加多個攔截器的時候不太美觀,讓我們再次利用面向對象思想封裝一下。我們設計一個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攔截器就是基於該組合進行開發。
二、Mybatis Plugin 插件概念
1、原理
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。
2、如何自定義攔截器?
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插件流程大致就是這樣了。
3、Mybatis四大接口
竟然Mybatis是對四大接口進行攔截的,那我們要先要知道Mybatis的四大接口對象 Executor
, StatementHandle
, ResultSetHandler
, ParameterHandler
。
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框架的整個執行過程。
三、Mybatis Plugin 插件源碼
經過上面的分析,再去看Mybastis Plugin 源碼的時候就很輕松了。
這幾個也就對應上面的幾個,只不過添加了注解,來判斷是否攔截指定方法。
1、攔截器鏈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);
}
}
這個就和我們上面實現的是一樣的。定義了攔截器鏈
2、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類。
3、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()]);
}
}
4、Interceptor接口
public interface Interceptor {
//攔截
Object intercept(Invocation invocation) throws Throwable;
//插入
Object plugin(Object target);
//設置屬性(擴展)
void setProperties(Properties properties);
}
思路
這么下來思路就很清晰了,我們通過實現Interceptor類實現自定義攔截器,然后把它放入InterceptorChain(攔截器鏈)中,然后通過JDK動態代理來實現依次攔截處理。
致謝
非常感謝一篇博客,它講的循序漸進,讓我不僅僅對JDK動態代理+責任鏈模式有更好的理解,而且在代碼設計上也有很大的啟發,確實受益很大。非常感謝!
我相信,無論今后的道路多么坎坷,只要抓住今天,遲早會在奮斗中嘗到人生的甘甜。抓住人生中的一分一秒,勝過虛度中的一月一年!(6)