日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MyBatis拦截器原理探究MyBatis拦截器原理探究

發(fā)布時間:2025/3/21 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis拦截器原理探究MyBatis拦截器原理探究 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

MyBatis攔截器介紹

MyBatis提供了一種插件(plugin)的功能,雖然叫做插件,但其實這是攔截器功能。那么攔截器攔截MyBatis中的哪些內容呢?

我們進入官網(wǎng)看一看:

MyBatis攔截器介紹

MyBatis提供了一種插件(plugin)的功能,雖然叫做插件,但其實這是攔截器功能。那么攔截器攔截MyBatis中的哪些內容呢?

我們進入官網(wǎng)看一看:

MyBatis 允許你在已映射語句執(zhí)行過程中的某一點進行攔截調用。默認情況下,MyBatis 允許使用插件來攔截的方法調用包括: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ù)的處理

攔截結果集的處理

攔截Sql語法構建的處理

攔截器的使用

攔截器介紹及配置

首先我們看下MyBatis攔截器的接口定義:

public interface Interceptor {

Object intercept(Invocation invocation) throws Throwable;

Object plugin(Object target);

void setProperties(Properties properties);

}

比較簡單,只有3個方法。 MyBatis默認沒有一個攔截器接口的實現(xiàn)類,開發(fā)者們可以實現(xiàn)符合自己需求的攔截器。

下面的MyBatis官網(wǎng)的一個攔截器實例:

@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配置:

這個攔截器攔截Executor接口的update方法(其實也就是SqlSession的新增,刪除,修改操作),所有執(zhí)行executor的update方法都會被該攔截器攔截到。

源碼分析

下面我們分析一下這段代碼背后的源碼。

首先從源頭->配置文件開始分析:

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);

}

}

}

具體的解析代碼其實比較簡單,就不貼了,主要就是通過反射實例化plugin節(jié)點中的interceptor屬性表示的類。然后調用全局配置類Configuration的addInterceptor方法。

public void addInterceptor(Interceptor interceptor) {

interceptorChain.addInterceptor(interceptor);

}

這個interceptorChain是Configuration的內部屬性,類型為InterceptorChain,也就是一個攔截器鏈,我們來看下它的定義:

public class InterceptorChain {

private final List interceptors = new ArrayList();

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 getInterceptors() {

return Collections.unmodifiableList(interceptors);

}

}

現(xiàn)在我們理解了攔截器配置的解析以及攔截器的歸屬,現(xiàn)在我們回過頭看下為何攔截器會攔截這些方法(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個方法都是Configuration的方法。這些方法在MyBatis的一個操作(新增,刪除,修改,查詢)中都會被執(zhí)行到,執(zhí)行的先后順序是Executor,ParameterHandler,ResultSetHandler,StatementHandler(其中ParameterHandler和ResultSetHandler的創(chuàng)建是在創(chuàng)建StatementHandler[3個可用的實現(xiàn)類CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler]的時候,其構造函數(shù)調用的[這3個實現(xiàn)類的構造函數(shù)其實都調用了父類BaseStatementHandler的構造函數(shù)])。

這4個方法實例化了對應的對象之后,都會調用interceptorChain的pluginAll方法,InterceptorChain的pluginAll剛才已經(jīng)介紹過了,就是遍歷所有的攔截器,然后調用各個攔截器的plugin方法。注意:攔截器的plugin方法的返回值會直接被賦值給原先的對象

由于可以攔截StatementHandler,這個接口主要處理sql語法的構建,因此比如分頁的功能,可以用攔截器實現(xiàn),只需要在攔截器的plugin方法中處理StatementHandler接口實現(xiàn)類中的sql即可,可使用反射實現(xiàn)。

MyBatis還提供了 @Intercepts和 @Signature關于攔截器的注解。官網(wǎng)的例子就是使用了這2個注解,還包括了Plugin類的使用:

@Override

public Object plugin(Object target) {

return Plugin.wrap(target, this);

}

下面我們就分析這3個 "新組合" 的源碼,首先先看Plugin類的wrap方法:

public static Object wrap(Object target, Interceptor interceptor) {

Map, Set> 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類實現(xiàn)了InvocationHandler接口,很明顯,我們看到這里返回了一個JDK自身提供的動態(tài)代理類。我們解剖一下這個方法調用的其他方法:

getSignatureMap方法:

private static Map, Set> 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, Set> signatureMap = new HashMap, Set>();

for (Signature sig : sigs) {

Set methods = signatureMap.get(sig.type());

if (methods == null) {

methods = new HashSet();

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方法解釋:首先會拿到攔截器這個類的 @Interceptors注解,然后拿到這個注解的屬性 @Signature注解集合,然后遍歷這個集合,遍歷的時候拿出 @Signature注解的type屬性(Class類型),然后根據(jù)這個type得到帶有method屬性和args屬性的Method。由于 @Interceptors注解的 @Signature屬性是一個屬性,所以最終會返回一個以type為key,value為Set的Map。

@Intercepts({@Signature(

type= Executor.class,

method = "update",

args = {MappedStatement.class,Object.class})})

比如這個 @Interceptors注解會返回一個key為Executor,value為集合(這個集合只有一個元素,也就是Method實例,這個Method實例就是Executor接口的update方法,且這個方法帶有MappedStatement和Object類型的參數(shù))。這個Method實例是根據(jù) @Signature的method和args屬性得到的。如果args參數(shù)跟type類型的method方法對應不上,那么將會拋出異常。

getAllInterfaces方法:

private static Class[] getAllInterfaces(Class type, Map, Set> signatureMap) {

Set> 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()]);

}

getAllInterfaces方法解釋:根據(jù)目標實例target(這個target就是之前所說的MyBatis攔截器可以攔截的類,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父類們,返回signatureMap中含有target實現(xiàn)的接口數(shù)組。

所以Plugin這個類的作用就是根據(jù) @Interceptors注解,得到這個注解的屬性 @Signature數(shù)組,然后根據(jù)每個 @Signature注解的type,method,args屬性使用反射找到對應的Method。最終根據(jù)調用的target對象實現(xiàn)的接口決定是否返回一個代理對象替代原先的target對象。

比如MyBatis官網(wǎng)的例子,當Configuration調用newExecutor方法的時候,由于Executor接口的update(MappedStatement ms, Object parameter)方法被攔截器被截獲。因此最終返回的是一個代理類Plugin,而不是Executor。這樣調用方法的時候,如果是個代理類,那么會執(zhí)行:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

try {

Set 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);

}

}

沒錯,如果找到對應的方法被代理之后,那么會執(zhí)行Interceptor接口的interceptor方法。

這個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方法也就是調用原先方法(不走代理)。

總結

MyBatis攔截器接口提供的3個方法中,plugin方法用于某些處理器(Handler)的構建過程。interceptor方法用于處理代理類的執(zhí)行。setProperties方法用于攔截器屬性的設置。

其實MyBatis官網(wǎng)提供的使用 @Interceptors和 @Signature注解以及Plugin類這樣處理攔截器的方法,我們不一定要直接這樣使用。我們也可以拋棄這3個類,直接在plugin方法內部根據(jù)target實例的類型做相應的操作。

總體來說MyBatis攔截器還是很簡單的,攔截器本身不需要太多的知識點,但是學習攔截器需要對MyBatis中的各個接口很熟悉,因為攔截器涉及到了各個接口的知識點。

歡迎工作一到五年想成為Java工程師的朋友們加入Java架構開發(fā):744677563

群內提供免費的Java架構學習資料(里面有高可用、高并發(fā)、高性能及分布式、Jvm性能調優(yōu)、Spring源碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用自己每一分每一秒的時間來學習提升自己,不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代!

總結

以上是生活随笔為你收集整理的MyBatis拦截器原理探究MyBatis拦截器原理探究的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。