Mybatis Plugin 插件(攔截器)原理分析
引言
最近在看mybatis 源碼亭畜,看到了mybatis plugin部分扮休,其實(shí)就是利用JDK動(dòng)態(tài)代理和責(zé)任鏈設(shè)計(jì)模式的綜合運(yùn)用。采用責(zé)任鏈模式拴鸵,通過動(dòng)態(tài)代理組織多個(gè)攔截器玷坠,通過這些攔截器你可以做一些你想做的事。具體分析從一個(gè)普通的需求功能開始:現(xiàn)在要對(duì)所有的接口方法做一個(gè)日志記錄和接口耗時(shí)記錄劲藐。
需求分析和功能實(shí)現(xiàn)
看到這個(gè)需求功能我默默的笑了八堡,這還不簡(jiǎn)單,每個(gè)方法我都加上不就行了嗎聘芜?就這么干兄渺,擼起袖子開始噼噼啪啪的敲打著鍵盤,慢慢發(fā)現(xiàn)太特么多方法了汰现,而且還是基本重復(fù)的溶耘,這樣寫下去不是辦法啊。這么多重復(fù)的是不是可以抽取出來呢服鹅,要堅(jiān)持 DRY(Don't repeat yourself)原則凳兵。這時(shí)候想到了代理設(shè)計(jì)模式,靜態(tài)代理模式肯定不行企软,這么多接口庐扫,得寫多少個(gè)代理類啊,還是用JDK的動(dòng)態(tài)代理吧
JDK動(dòng)態(tài)代理
public interface Target {
String execute(String name);
}
public class TargetImpl implements Target {
@Override
public String execute(String name) {
System.out.println("execute() "+ name);
return name;
}
}
public class TargetProxy implements InvocationHandler {
private Object target;
public TargetProxy(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(" 攔截前仗哨。形庭。。");
Object result = method.invoke(target, args);
System.out.println(" 攔截后厌漂。萨醒。。");
return result;
}
public static Object wrap(Object target) {
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),new TargetProxy(target));
}
}
public class Test {
public static void main(String[] args) {
Target target = new TargetImpl();
//返回的是代理對(duì)象苇倡,實(shí)現(xiàn)了Target接口富纸,
//實(shí)際調(diào)用方法的時(shí)候囤踩,是調(diào)用TargetProxy的invoke()方法
Target targetProxy = (Target) TargetProxy.wrap(target);
targetProxy.execute(" HelloWord ");
}
}
TargetProxy.wrap(target) 實(shí)際返回的對(duì)象類似下面這樣,這樣看起來就容易理解點(diǎn)了
public class $Proxy implements Target {
private InvocationHandler targetProxy
@Override
public String execute(String name) {
return targetProxy.invoke();
}
}
運(yùn)行結(jié)果:
攔截前晓褪。堵漱。。
execute() HelloWord
攔截后涣仿。勤庐。。
嗯好港,這思路是正確的了愉镰。但還是存在問題,execute() 是業(yè)務(wù)代碼钧汹,我把所有的要攔截處理的邏輯都寫到invoke方法里面了丈探,不符合面向?qū)ο蟮乃枷耄梢猿橄笠幌绿幚碚腹隆?梢栽O(shè)計(jì)一個(gè)Interceptor接口糊肠,需要做什么攔截處理實(shí)現(xiàn)接口就行了辨宠。
public interface Interceptor {
/**
* 具體攔截處理
*/
void intercept();
}
intercept() 方法就可以處理各種前期準(zhǔn)備了
public class LogInterceptor implements Interceptor {
@Override
public void intercept() {
System.out.println(" 記錄日志 ");
}
}
public class TransactionInterceptor implements Interceptor {
@Override
public void intercept() {
System.out.println(" 開啟事務(wù) ");
}
}
代理對(duì)象也做一下修改
public class TargetProxy 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) {
TargetProxy targetProxy = new TargetProxy(target, interceptorList);
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),targetProxy);
}
}
現(xiàn)在可以根據(jù)需要?jiǎng)討B(tài)的添加攔截器了,在每次執(zhí)行業(yè)務(wù)代碼execute(...)之前都會(huì)攔截货裹,看起來高級(jí)一丟丟了嗤形,來測(cè)試一下
public class Test {
public static void main(String[] args) {
List<Interceptor> interceptorList = new ArrayList<>();
interceptorList.add(new LogInterceptor());
interceptorList.add(new TransactionInterceptor());
Target target = new TargetImpl();
Target targetProxy = (Target) TargetProxy.wrap(target,interceptorList);
targetProxy.execute(" HelloWord ");
}
}
執(zhí)行結(jié)果:
記錄日志
開啟事務(wù)
execute() HelloWord
貌似有哪里不太對(duì)一樣,按照上面這種我們只能做前置攔截弧圆,而且攔截器并不知道攔截對(duì)象的信息赋兵。應(yīng)該做更一步的抽象,把攔截對(duì)象信息進(jìn)行封裝搔预,作為攔截器攔截方法的參數(shù)霹期,把攔截目標(biāo)對(duì)象真正的執(zhí)行方法放到Interceptor中完成,這樣就可以實(shí)現(xiàn)前后攔截拯田,并且還能對(duì)攔截對(duì)象的參數(shù)等做修改历造。設(shè)計(jì)一個(gè)Invocation 對(duì)象
public class Invocation {
/**
* 目標(biāo)對(duì)象
*/
private Object target;
/**
* 執(zhí)行的方法
*/
private Method method;
/**
* 方法的參數(shù)
*/
private Object[] args;
//省略getset
public Invocation(Object target, Method method, Object[] args) {
this.target = target;
this.method = method;
this.args = args;
}
/**
* 執(zhí)行目標(biāo)對(duì)象的方法
* @return
* @throws Exception
*/
public Object process() throws Exception{
return method.invoke(target,args);
}
}
攔截接口做修改
public interface Interceptor {
/**
* 具體攔截處理
* @param invocation
* @return
* @throws Exception
*/
Object intercept(Invocation invocation) throws Exception;
}
Invocation 類就是被代理對(duì)象的封裝,也就是要攔截的真正對(duì)象船庇。TargetProxy修改如下:
public class TargetProxy 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) {
TargetProxy targetProxy = new TargetProxy(target, interceptor);
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),targetProxy);
}
}
public class TransactionInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Exception{
System.out.println(" 開啟事務(wù) ");
Object result = invocation.process();
System.out.println(" 提交事務(wù) ");
return result;
}
}
public class Test {
public static void main(String[] args) {
Target target = new TargetImpl();
Interceptor transactionInterceptor = new TransactionInterceptor();
Target targetProxy = (Target) TargetProxy.wrap(target,transactionInterceptor);
targetProxy.execute(" HelloWord ");
}
}
運(yùn)行結(jié)果:
開啟事務(wù)
execute() HelloWord
提交事務(wù)
這樣就能實(shí)現(xiàn)前后攔截吭产,并且攔截器能獲取攔截對(duì)象信息,這樣擴(kuò)展性就好很多了鸭轮。但是測(cè)試?yán)拥倪@樣調(diào)用看著很別扭臣淤,對(duì)應(yīng)目標(biāo)類來說,只需要了解對(duì)他插入了什么攔截就好窃爷。再修改一下邑蒋,在攔截器增加一個(gè)插入目標(biāo)類的方法
public interface Interceptor {
/**
* 具體攔截處理
* @param invocation
* @return
* @throws Exception
*/
Object intercept(Invocation invocation) throws Exception;
/**
* 插入目標(biāo)類
* @param target
* @return
*/
Object plugin(Object target);
}
public class TransactionInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Exception{
System.out.println(" 開啟事務(wù) ");
Object result = invocation.process();
System.out.println(" 提交事務(wù) ");
return result;
}
@Override
public Object plugin(Object target) {
return TargetProxy.wrap(target,this);
}
}
這樣目標(biāo)類僅僅需要在執(zhí)行前姓蜂,插入需要的攔截器就好了,測(cè)試代碼:
public class Test {
public static void main(String[] args) {
Target target = new TargetImpl();
Interceptor transactionInterceptor = new TransactionInterceptor();
//把事務(wù)攔截器插入到目標(biāo)類中
target = (Target) transactionInterceptor.plugin(target);
target.execute(" HelloWord ");
}
}
運(yùn)行結(jié)果:
開啟事務(wù)
execute() HelloWord
提交事務(wù)
到這里就差不多完成了寺董,可能有同學(xué)可能會(huì)有疑問覆糟,那我要添加多個(gè)攔截器呢,怎么搞遮咖?
public class Test {
public static void main(String[] args) {
Target target = new TargetImpl();
Interceptor transactionInterceptor = new TransactionInterceptor();
target = (Target) transactionInterceptor.plugin(target);
LogInterceptor logInterceptor = new LogInterceptor();
target = (Target)logInterceptor.plugin(target);
target.execute(" HelloWord ");
}
}
運(yùn)行結(jié)果:
開始記錄日志
開啟事務(wù)
execute() HelloWord
提交事務(wù)
結(jié)束記錄日志
其實(shí)這就是代理嵌套再代理滩字,下圖是執(zhí)行的時(shí)序圖,每個(gè)步驟就不做詳細(xì)的說明了
責(zé)任鏈
其實(shí)上面已經(jīng)實(shí)現(xiàn)的沒問題了御吞,只是還差那么一點(diǎn)點(diǎn)麦箍,添加多個(gè)攔截器的時(shí)候不太美觀,讓我們?cè)俅卫妹嫦驅(qū)ο笏枷敕庋b一下陶珠。我們?cè)O(shè)計(jì)一個(gè)InterceptorChain 攔截器鏈類
public class InterceptorChain {
private List<Interceptor> interceptorList = new ArrayList<>();
/**
* 插入所有攔截器
* @param target
* @return
*/
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptorList) {
target = interceptor.plugin(target);
}
return target;
}
public void addInterceptor(Interceptor interceptor) {
interceptorList.add(interceptor);
}
/**
* 返回一個(gè)不可修改集合挟裂,只能通過addInterceptor方法添加
* 這樣控制權(quán)就在自己手里
* @return
*/
public List<Interceptor> getInterceptorList() {
return Collections.unmodifiableList(interceptorList);
}
}
其實(shí)就是通過pluginAll() 方法包一層把所有的攔截器插入到目標(biāo)類去而已。測(cè)試代碼:
public class Test {
public static void main(String[] args) {
Target target = new TargetImpl();
Interceptor transactionInterceptor = new TransactionInterceptor();
LogInterceptor logInterceptor = new LogInterceptor();
InterceptorChain interceptorChain = new InterceptorChain();
interceptorChain.addInterceptor(transactionInterceptor);
interceptorChain.addInterceptor(logInterceptor);
target = (Target) interceptorChain.pluginAll(target);
target.execute(" HelloWord ");
}
}
Mybatis Plugin 插件分析
經(jīng)過上面的分析揍诽,再去看mybastis plugin 源碼的時(shí)候就很輕松了诀蓉。
有沒有覺得似曾相似的感覺呢,沒錯(cuò)你的感覺是對(duì)的暑脆,這基本和我們上面的最終實(shí)現(xiàn)是一致的渠啤,Plugin 相當(dāng)于我們的TargetProxy。
Mybatis Plugin 介紹及配置使用
MyBatis 允許你在已映射語(yǔ)句執(zhí)行過程中的某一點(diǎn)進(jìn)行攔截調(diào)用添吗。默認(rèn)情況下沥曹,MyBatis允許使用插件來攔截的方法調(diào)用包括:
1.Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) 攔截執(zhí)行器的方法;
2.ParameterHandler (getParameterObject, setParameters) 攔截參數(shù)的處理碟联;
3.ResultSetHandler (handleResultSets, handleOutputParameters) 攔截結(jié)果集的處理妓美;
4.StatementHandler (prepare, parameterize, batch, update, query) 攔截Sql語(yǔ)法構(gòu)建的處理
參考Mybatis 官方的一個(gè)例子:
-
在全局配置文件mybatis-config.xml 添加
<plugins> <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin> </plugins>
-
寫好攔截類代碼
@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) { } }
這個(gè)攔截器會(huì)攔截Executor接口的update方法
源碼簡(jiǎn)要分析
首先從配置文件解析開始
public class XMLConfigBuilder extends BaseBuilder {
//解析配置
private void parseConfiguration(XNode root) {
try {
//省略部分代碼
pluginElement(root.evalNode("plugins"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
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);
//調(diào)用InterceptorChain.addInterceptor
configuration.addInterceptor(interceptorInstance);
}
}
}
}
上面的代碼主要是解析配置文件的plugin節(jié)點(diǎn),根據(jù)配置的interceptor 屬性實(shí)例化Interceptor 對(duì)象鲤孵,然后添加到Configuration 對(duì)象中的InterceptorChain 屬性中
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
public Object pluginAll(Object target) {
//循環(huán)調(diào)用每個(gè)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);
}
}
這個(gè)就和我們上面實(shí)現(xiàn)的是一樣的壶栋。定義了攔截器鏈,初始化配置文件的時(shí)候就把所有的攔截器添加到攔截器鏈中普监,下面來看一下什么時(shí)候把攔截器插入到需要攔截的接口中
public class Configuration {
protected final InterceptorChain interceptorChain = new InterceptorChain();
//創(chuàng)建參數(shù)處理器
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
//創(chuàng)建ParameterHandler
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
//插件在這里插入
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
//創(chuàng)建結(jié)果集處理器
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
//創(chuàng)建DefaultResultSetHandler
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
//插件在這里插入
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
//創(chuàng)建語(yǔ)句處理器
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
//創(chuàng)建路由選擇語(yǔ)句處理器
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);
}
//產(chǎn)生執(zhí)行器
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
//這句再做一下保護(hù),囧,防止粗心大意的人將defaultExecutorType設(shè)成null?
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
//然后就是簡(jiǎn)單的3個(gè)分支委刘,產(chǎn)生3種執(zhí)行器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(默認(rèn)就是有緩存),裝飾者模式,所以默認(rèn)都是返回CachingExecutor
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
//此處調(diào)用插件,通過插件可以改變Executor行為
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
}
從代碼可以看出mybatis 在實(shí)例化Executor鹰椒、ParameterHandler锡移、ResultSetHandler、StatementHandler四大接口對(duì)象的時(shí)候調(diào)用interceptorChain.pluginAll() 方法插入進(jìn)去的漆际。其實(shí)就是循環(huán)執(zhí)行攔截器鏈所有的攔截器的plugin() 方法淆珊,mybatis官方推薦的plugin方法是Plugin.wrap() 方法,這個(gè)類就是我們上面的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);
//產(chǎn)生代理,是Interceptor注解的接口的實(shí)現(xiàn)類才會(huì)產(chǎn)生代理
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實(shí)現(xiàn)類注解的方法才會(huì)攔截處理
if (methods != null && methods.contains(method)) {
//調(diào)用Interceptor.intercept奸汇,也即插入了我們自己的邏輯
return interceptor.intercept(new Invocation(target, method, args));
}
//最后還是執(zhí)行原來邏輯
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
//取得簽名Map,就是獲取Interceptor實(shí)現(xiàn)類上面的注解施符,要攔截的是那個(gè)類(Executor往声,ParameterHandler, ResultSetHandler戳吝,StatementHandler)的那個(gè)方法
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
//取Intercepts注解浩销,例子可參見ExamplePlugin.java
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
//必須得有Intercepts注解,沒有報(bào)錯(cuò)
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
//value是數(shù)組型听哭,Signature的數(shù)組
Signature[] sigs = interceptsAnnotation.value();
//每個(gè)class里有多個(gè)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()]);
}
}
總結(jié)
Mybatis 攔截器的使用是實(shí)現(xiàn)Interceptor接口
public interface Interceptor {
//攔截
Object intercept(Invocation invocation) throws Throwable;
//插入
Object plugin(Object target);
//設(shè)置屬性(擴(kuò)展)
void setProperties(Properties properties);
}
通過上面的分析可以知道慢洋,所有可能被攔截的處理類都會(huì)生成一個(gè)代理類,如果有N個(gè)攔截器,就會(huì)有N個(gè)代理陆盘,層層生成動(dòng)態(tài)代理是比較耗性能的普筹。而且雖然能指定插件攔截的位置,但這個(gè)是在執(zhí)行方法時(shí)利用反射動(dòng)態(tài)判斷的隘马,初始化的時(shí)候就是簡(jiǎn)單的把攔截器插入到了所有可以攔截的地方太防。所以盡量不要編寫不必要的攔截器。