MyBatis插件機制超詳細講解
MyBatis的插件機制
MyBatis 允許在已映射語句執(zhí)行過程中的某一點進行攔截調(diào)用。默認情況下,MyBatis 允許使用插件來攔截的方法調(diào)用包括:
- Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler(getParameterObject, setParameters)
- ResultSetHandler(handleResultSets, handleOutputParameters)
- StatementHandler(prepare, parameterize, batch, update, query)
這里我們再回顧一下,在創(chuàng)建StatementHandler時,我們看到了如下代碼:
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;
}
InterceptorChain
在全局配置Configuration中維護了一個InterceptorChain interceptorChain = new InterceptorChain()攔截器鏈,其內(nèi)部維護了一個私有常量List<Interceptor> interceptors,其pluginAll方法為遍歷interceptors并調(diào)用每個攔截器的plugin方法。
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
public Object pluginAll(Object target) {
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);
}
}MyBatis中攔截器接口
package org.apache.ibatis.plugin;
import java.util.Properties;
public interface Interceptor {
//攔截處理,也就是代理對象目標方法執(zhí)行前被處理
Object intercept(Invocation invocation) throws Throwable;
//生成代理對象
Object plugin(Object target);
//設置屬性
void setProperties(Properties properties);
}
如果想自定義插件,那么就需要實現(xiàn)該接口。
MyBatis中的Invocation
package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Invocation {
//目標對象
private final Object target;
//目標對象的方法
private final Method method;
//方法參數(shù)
private final Object[] args;
public Invocation(Object target, Method method, Object[] args) {
this.target = target;
this.method = method;
this.args = args;
}
public Object getTarget() { return target;}
public Method getMethod() {return method;}
public Object[] getArgs() {return args;}
//proceed-繼續(xù),也就是說流程繼續(xù)往下執(zhí)行,這里看方法就是目標方法反射調(diào)用。
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}MyBatis中的Plugin
package org.apache.ibatis.plugin;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.reflection.ExceptionUtil;
public class Plugin implements InvocationHandler {
//目標對象 ,被代理的對象
private final Object target;
//攔截器
private final Interceptor interceptor;
//方法簽名集合
private final Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
//該方法會獲取signatureMap中包含的所有target實現(xiàn)的接口,然后生成代理對象
public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
//每一個InvocationHandler 的invoke方法會在代理對象的目標方法執(zhí)行前被觸發(fā)
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
//獲取攔截器感興趣的接口與方法
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
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;
}
//該方法會獲取signatureMap中包含的所有type實現(xiàn)的接口與上級接口
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<>();
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()]);
}
}這里Plugin實現(xiàn)了InvocationHandler,那么其invoke方法會在代理對象的目標方法執(zhí)行前被觸發(fā)。其invoke方法解釋如下:
- ① 獲取當前Plugin感興趣的方法類型,判斷目標方法Method是否被包含;
- ② 如果當前目標方法是Plugin感興趣的,那么就
interceptor.intercept(new Invocation(target, method, args));觸發(fā)攔截器的intercept方法; - ③ 如果當前目標方法不是Plugin感興趣的,直接執(zhí)行目標方法。
上面說Plugin感興趣其實是指內(nèi)部的interceptor感興趣。
MyBatis插件開發(fā)
如下所示,編寫插件實現(xiàn)Interceptor接口,并使用@Intercepts注解完成插件簽名。
package com.mybatis.dao;
import java.util.Properties;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
/**
* 完成插件簽名:告訴MyBatis當前插件用來攔截哪個對象的哪個方法
*/
@Intercepts({@Signature(type=StatementHandler.class,method="parameterize",args=java.sql.Statement.class)})
public class MyFirstPlugin implements Interceptor{
@Override
public Object intercept(Invocation invocation) throws Throwable {
// TODO Auto-generated method stub
System.out.println("MyFirstPlugin...intercept:"+invocation.getMethod());
Object target = invocation.getTarget();
System.out.println("當前攔截到的對象:"+target);
//拿到:StatementHandler==>ParameterHandler===>parameterObject
//拿到target的元數(shù)據(jù)
MetaObject metaObject = SystemMetaObject.forObject(target);
Object value = metaObject.getValue("parameterHandler.parameterObject");
System.out.println("sql語句用的參數(shù)是:"+value);
//修改完sql語句要用的參數(shù)
metaObject.setValue("parameterHandler.parameterObject", 11);
//執(zhí)行目標方法
Object proceed = invocation.proceed();
//返回執(zhí)行后的返回值
return proceed;
}
//plugin:包裝目標對象的:包裝:為目標對象創(chuàng)建一個代理對象
@Override
public Object plugin(Object target) {
//我們可以借助Plugin的wrap方法來使用當前Interceptor包裝我們目標對象
System.out.println("MyFirstPlugin...plugin:mybatis將要包裝的對象"+target);
Object wrap = Plugin.wrap(target, this);
//返回為當前target創(chuàng)建的動態(tài)代理
return wrap;
}
//setProperties:將插件注冊時 的property屬性設置進來
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
System.out.println("插件配置的信息:"+properties);
}
}注冊到mybatis的全局配置文件中,示例如下(注意,插件是可以設置屬性的如這里我們可以設置用戶名、密碼):
<plugins>
<plugin interceptor="com.mybatis.dao.MyFirstPlugin">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</plugin>
</plugins>
那么mybatis在執(zhí)行過程中實例化Executor、ParameterHandler、ResultSetHandler和StatementHandler時都會觸發(fā)上面我們自定義插件的plugin方法。
如果有多個插件,那么攔截器鏈包裝的時候會從前到后,執(zhí)行的時候會從后到前。如這里生成的StatementHandler代理對象如下:

總結(jié)
- 按照插件注解聲明,按照插件配置順序調(diào)用插件
plugin方法,生成被攔截對象的動態(tài)代理; - 多個插件依次生成目標對象的代理對象,層層包裹,先聲明的先包裹,形成代理鏈;
- 目標方法執(zhí)行時依次從外到內(nèi)執(zhí)行插件的
intercept方法。 - 多個插件情況下,我們往往需要在某個插件中分離出目標對象??梢越柚?code>MyBatis提供的
SystemMetaObject類來進行獲取最后一層的h以及target屬性的值
到此這篇關(guān)于MyBatis插件機制超詳細講解的文章就介紹到這了,更多相關(guān)MyBatis插件機制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatisPlus代碼生成器的原理及實現(xiàn)詳解
這篇文章主要為大家詳細介紹了MyBatisPlus中代碼生成器的原理及實現(xiàn),文中的示例代碼講解詳細,對我們學習MyBatisPlus有一定幫助,需要的可以參考一下2022-08-08
SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn)
這篇文章主要介紹了SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03

