MyBatis攔截器原理探究
MyBatis攔截器介紹
MyBatis提供了一種插件(plugin)的功能,雖然叫做插件,但其實(shí)這是攔截器功能。那么攔截器攔截MyBatis中的哪些內(nèi)容呢?
我們進(jìn)入官網(wǎng)看一看:
MyBatis 允許你在已映射語(yǔ)句執(zhí)行過(guò)程中的某一點(diǎn)進(jìn)行攔截調(diào)用。默認(rèn)情況下,MyBatis 允許使用插件來(lái)攔截的方法調(diào)用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
我們看到了可以攔截Executor接口的部分方法,比如update,query,commit,rollback等方法,還有其他接口的一些方法
等。
總體概括為:
- 攔截執(zhí)行器的方法
- 攔截參數(shù)的處理
- 攔截結(jié)果集的處理
- 攔截Sql語(yǔ)法構(gòu)建的處理
攔截器的使用
攔截器介紹及配置
首先我們看下MyBatis攔截器的接口定義:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
比較簡(jiǎn)單,只有3個(gè)方法。 MyBatis默認(rèn)沒(méi)有一個(gè)攔截器接口的實(shí)現(xiàn)類,開(kāi)發(fā)者們可以實(shí)現(xiàn)符合自己需求的攔截器。
下面的MyBatis官網(wǎng)的一個(gè)攔截器實(shí)例:
@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) {
}
}
全局xml配置:
<plugins> <plugin interceptor="org.format.mybatis.cache.interceptor.ExamplePlugin"></plugin> </plugins>
這個(gè)攔截器攔截Executor接口的update方法(其實(shí)也就是SqlSession的新增,刪除,修改操作),所有執(zhí)行executor的update方法都會(huì)被該攔截器攔截到。
源碼分析
下面我們分析一下這段代碼背后的源碼。
首先從源頭->配置文件開(kāi)始分析:
XMLConfigBuilder解析MyBatis全局配置文件的pluginElement私有方法:
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);
configuration.addInterceptor(interceptorInstance);
}
}
}
具體的解析代碼其實(shí)比較簡(jiǎn)單,就不貼了,主要就是通過(guò)反射實(shí)例化plugin節(jié)點(diǎn)中的interceptor屬性表示的類。然后調(diào)用全局配置類Configuration的addInterceptor方法。
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
}
這個(gè)interceptorChain是Configuration的內(nèi)部屬性,類型為InterceptorChain,也就是一個(gè)攔截器鏈,我們來(lái)看下它的定義:
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);
}
}
現(xiàn)在我們理解了攔截器配置的解析以及攔截器的歸屬,現(xiàn)在我們回過(guò)頭看下為何攔截器會(huì)攔截這些方法(Executor,ParameterHandler,ResultSetHandler,StatementHandler的部分方法):
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
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) {
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, ExecutorType executorType, boolean autoCommit) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
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);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor, autoCommit);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
以上4個(gè)方法都是Configuration的方法。這些方法在MyBatis的一個(gè)操作(新增,刪除,修改,查詢)中都會(huì)被執(zhí)行到,執(zhí)行的先后順序是Executor,ParameterHandler,ResultSetHandler,StatementHandler(其中ParameterHandler和ResultSetHandler的創(chuàng)建是在創(chuàng)建StatementHandler[3個(gè)可用的實(shí)現(xiàn)類CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler]的時(shí)候,其構(gòu)造函數(shù)調(diào)用的[這3個(gè)實(shí)現(xiàn)類的構(gòu)造函數(shù)其實(shí)都調(diào)用了父類BaseStatementHandler的構(gòu)造函數(shù)])。
這4個(gè)方法實(shí)例化了對(duì)應(yīng)的對(duì)象之后,都會(huì)調(diào)用interceptorChain的pluginAll方法,InterceptorChain的pluginAll剛才已經(jīng)介紹過(guò)了,就是遍歷所有的攔截器,然后調(diào)用各個(gè)攔截器的plugin方法。注意:攔截器的plugin方法的返回值會(huì)直接被賦值給原先的對(duì)象
由于可以攔截StatementHandler,這個(gè)接口主要處理sql語(yǔ)法的構(gòu)建,因此比如分頁(yè)的功能,可以用攔截器實(shí)現(xiàn),只需要在攔截器的plugin方法中處理StatementHandler接口實(shí)現(xiàn)類中的sql即可,可使用反射實(shí)現(xiàn)。
MyBatis還提供了 @Intercepts和 @Signature關(guān)于攔截器的注解。官網(wǎng)的例子就是使用了這2個(gè)注解,還包括了Plugin類的使用:
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
下面我們就分析這3個(gè) "新組合" 的源碼,首先先看Plugin類的wrap方法:
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;
}
Plugin類實(shí)現(xiàn)了InvocationHandler接口,很明顯,我們看到這里返回了一個(gè)JDK自身提供的動(dòng)態(tài)代理類。我們解剖一下這個(gè)方法調(diào)用的其他方法:
getSignatureMap方法:
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
if (interceptsAnnotation == null) { // issue #251
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
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;
}
getSignatureMap方法解釋:首先會(huì)拿到攔截器這個(gè)類的 @Interceptors注解,然后拿到這個(gè)注解的屬性 @Signature注解集合,然后遍歷這個(gè)集合,遍歷的時(shí)候拿出 @Signature注解的type屬性(Class類型),然后根據(jù)這個(gè)type得到帶有method屬性和args屬性的Method。由于 @Interceptors注解的 @Signature屬性是一個(gè)屬性,所以最終會(huì)返回一個(gè)以type為key,value為Set<Method>的Map。
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
比如這個(gè) @Interceptors注解會(huì)返回一個(gè)key為Executor,value為集合(這個(gè)集合只有一個(gè)元素,也就是Method實(shí)例,這個(gè)Method實(shí)例就是Executor接口的update方法,且這個(gè)方法帶有MappedStatement和Object類型的參數(shù))。這個(gè)Method實(shí)例是根據(jù) @Signature的method和args屬性得到的。如果args參數(shù)跟type類型的method方法對(duì)應(yīng)不上,那么將會(huì)拋出異常。
getAllInterfaces方法:
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()]);
}
getAllInterfaces方法解釋:根據(jù)目標(biāo)實(shí)例target(這個(gè)target就是之前所說(shuō)的MyBatis攔截器可以攔截的類,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父類們,返回signatureMap中含有target實(shí)現(xiàn)的接口數(shù)組。
所以Plugin這個(gè)類的作用就是根據(jù) @Interceptors注解,得到這個(gè)注解的屬性 @Signature數(shù)組,然后根據(jù)每個(gè) @Signature注解的type,method,args屬性使用反射找到對(duì)應(yīng)的Method。最終根據(jù)調(diào)用的target對(duì)象實(shí)現(xiàn)的接口決定是否返回一個(gè)代理對(duì)象替代原先的target對(duì)象。
比如MyBatis官網(wǎng)的例子,當(dāng)Configuration調(diào)用newExecutor方法的時(shí)候,由于Executor接口的update(MappedStatement ms, Object parameter)方法被攔截器被截獲。因此最終返回的是一個(gè)代理類Plugin,而不是Executor。這樣調(diào)用方法的時(shí)候,如果是個(gè)代理類,那么會(huì)執(zhí)行:
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);
}
}
沒(méi)錯(cuò),如果找到對(duì)應(yīng)的方法被代理之后,那么會(huì)執(zhí)行Interceptor接口的interceptor方法。
這個(gè)Invocation類如下:
public class Invocation {
private Object target;
private Method method;
private 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;
}
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}
它的proceed方法也就是調(diào)用原先方法(不走代理)。
總結(jié)
MyBatis攔截器接口提供的3個(gè)方法中,plugin方法用于某些處理器(Handler)的構(gòu)建過(guò)程。interceptor方法用于處理代理類的執(zhí)行。setProperties方法用于攔截器屬性的設(shè)置。
其實(shí)MyBatis官網(wǎng)提供的使用 @Interceptors和 @Signature注解以及Plugin類這樣處理攔截器的方法,我們不一定要直接這樣使用。我們也可以拋棄這3個(gè)類,直接在plugin方法內(nèi)部根據(jù)target實(shí)例的類型做相應(yīng)的操作。
總體來(lái)說(shuō)MyBatis攔截器還是很簡(jiǎn)單的,攔截器本身不需要太多的知識(shí)點(diǎn),但是學(xué)習(xí)攔截器需要對(duì)MyBatis中的各個(gè)接口很熟悉,因?yàn)閿r截器涉及到了各個(gè)接口的知識(shí)點(diǎn)。
總結(jié)
以上所述是小編給大家介紹的MyBatis攔截器原理探究,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Java設(shè)計(jì)模式七大原則之合成復(fù)用原則詳解
合成復(fù)用原則(Composite Reuse Principle),即盡量使用組合/聚合的方式,而不是使用繼承。本文將為大家具體介紹一下Java設(shè)計(jì)模式七大原則之一的合成復(fù)用原則,需要的可以參考一下2022-02-02
SpringBoot啟動(dòng)過(guò)程的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot啟動(dòng)過(guò)程的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
如何解決Maven無(wú)法拉取SNAPSHOT依賴問(wèn)題
在使用Maven管理項(xiàng)目時(shí),可能會(huì)遇到無(wú)法拉取SNAPSHOT版本依賴的問(wèn)題,這通常是因?yàn)镸aven默認(rèn)不支持直接拉取SNAPSHOT版本,遇到這樣的問(wèn)題,可以通過(guò)在項(xiàng)目的pom.xml文件中添加<repositories>標(biāo)簽,并配置啟用SNAPSHOT的倉(cāng)庫(kù)地址來(lái)解決2024-10-10
Java實(shí)現(xiàn)平滑加權(quán)輪詢算法之降權(quán)和提權(quán)詳解
所有負(fù)載均衡的場(chǎng)景幾乎都會(huì)用到這個(gè)平滑加權(quán)輪詢算法,下面這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)平滑加權(quán)輪詢算法之降權(quán)和提權(quán)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
Spring常用注解 使用注解來(lái)構(gòu)造IoC容器的方法
下面小編就為大家分享一篇Spring常用注解 使用注解來(lái)構(gòu)造IoC容器的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
java客戶端Etcd官方倉(cāng)庫(kù)jetcd中KeepAlive接口實(shí)現(xiàn)
這篇文章主要為大家介紹了java客戶端Etcd官方倉(cāng)庫(kù)jetcd中KeepAlive接口實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,多多加薪2022-02-02
關(guān)于SpringCloud灰度發(fā)布的實(shí)現(xiàn)
這篇文章主要介紹了關(guān)于SpringCloud灰度發(fā)布的實(shí)現(xiàn),灰度發(fā)布又稱金絲雀發(fā)布,是在系統(tǒng)升級(jí)的時(shí)候能夠平滑過(guò)渡的一種發(fā)布方式,灰度發(fā)布可以保證整體系統(tǒng)的穩(wěn)定,在初始灰度的時(shí)候就可以發(fā)現(xiàn)、調(diào)整問(wèn)題,以保證其影響度,需要的朋友可以參考下2023-08-08
SpringBoot+mybatis實(shí)現(xiàn)多數(shù)據(jù)源支持操作
這篇文章主要介紹了SpringBoot+mybatis實(shí)現(xiàn)多數(shù)據(jù)源支持操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10

