MyBatis拦截器介绍

MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截MyBatis中的哪些内容呢?

我们进入官网看一看:

MyBatis拦截器介绍

MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截MyBatis中的哪些内容呢?

我们进入官网看一看:

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,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等方法,还有其他接口的一些方法等。

总体概括为:

拦截执行器的方法

拦截参数的处理

拦截结果集的处理

拦截Sql语法构建的处理

拦截器的使用

拦截器介绍及配置

首先我们看下MyBatis拦截器的接口定义:

public interface Interceptor {

Object intercept(Invocation invocation) throws Throwable;

Object plugin(Object target);

void setProperties(Properties properties);

}

比较简单,只有3个方法。 MyBatis默认没有一个拦截器接口的实现类,开发者们可以实现符合自己需求的拦截器。

下面的MyBatis官网的一个拦截器实例:

@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的新增,删除,修改操作),所有执行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节点中的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);

}

}

现在我们理解了拦截器配置的解析以及拦截器的归属,现在我们回过头看下为何拦截器会拦截这些方法(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的一个操作(新增,删除,修改,查询)中都会被执行到,执行的先后顺序是Executor,ParameterHandler,ResultSetHandler,StatementHandler(其中ParameterHandler和ResultSetHandler的创建是在创建StatementHandler[3个可用的实现类CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler]的时候,其构造函数调用的[这3个实现类的构造函数其实都调用了父类BaseStatementHandler的构造函数])。

这4个方法实例化了对应的对象之后,都会调用interceptorChain的pluginAll方法,InterceptorChain的pluginAll刚才已经介绍过了,就是遍历所有的拦截器,然后调用各个拦截器的plugin方法。注意:拦截器的plugin方法的返回值会直接被赋值给原先的对象

由于可以拦截StatementHandler,这个接口主要处理sql语法的构建,因此比如分页的功能,可以用拦截器实现,只需要在拦截器的plugin方法中处理StatementHandler接口实现类中的sql即可,可使用反射实现。

MyBatis还提供了 @Intercepts和 @Signature关于拦截器的注解。官网的例子就是使用了这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类实现了InvocationHandler接口,很明显,我们看到这里返回了一个JDK自身提供的动态代理类。我们解剖一下这个方法调用的其他方法:

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类型),然后根据这个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类型的参数)。这个Method实例是根据 @Signature的method和args属性得到的。如果args参数跟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方法解释:根据目标实例target(这个target就是之前所说的MyBatis拦截器可以拦截的类,Executor,ParameterHandler,ResultSetHandler,StatementHandler)和它的父类们,返回signatureMap中含有target实现的接口数组。

所以Plugin这个类的作用就是根据 @Interceptors注解,得到这个注解的属性 @Signature数组,然后根据每个 @Signature注解的type,method,args属性使用反射找到对应的Method。最终根据调用的target对象实现的接口决定是否返回一个代理对象替代原先的target对象。

比如MyBatis官网的例子,当Configuration调用newExecutor方法的时候,由于Executor接口的update(MappedStatement ms, Object parameter)方法被拦截器被截获。因此最终返回的是一个代理类Plugin,而不是Executor。这样调用方法的时候,如果是个代理类,那么会执行:

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

}

}

没错,如果找到对应的方法被代理之后,那么会执行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方法用于处理代理类的执行。setProperties方法用于拦截器属性的设置。

其实MyBatis官网提供的使用 @Interceptors和 @Signature注解以及Plugin类这样处理拦截器的方法,我们不一定要直接这样使用。我们也可以抛弃这3个类,直接在plugin方法内部根据target实例的类型做相应的操作。

总体来说MyBatis拦截器还是很简单的,拦截器本身不需要太多的知识点,但是学习拦截器需要对MyBatis中的各个接口很熟悉,因为拦截器涉及到了各个接口的知识点。

欢迎工作一到五年想成为Java工程师的朋友们加入Java架构开发:744677563

群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!

MyBatis拦截器原理探究MyBatis拦截器原理探究相关推荐

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

    MyBatis拦截器介绍 MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能.那么拦截器拦截MyBatis中的哪些内容呢? 我们进入官网看一看: MyBatis拦截 ...

  2. mybatis拦截器实现数据脱敏拦截器使用

    目录 1.主要代码如下: 1.注解 2.定义枚举脱敏规则 3.增加mybatis拦截器 4.Javabean中增加注解,如果是查询返回的map,会根据desensitionMap的规则进行脱敏 2.原 ...

  3. list mybatis 接收 类型_基于mybatis拦截器实现的一款简易影子表自动切换插件

    近期因工作需要,小编基于mybatis拦截器开发了一款简易影子表自动切换插件,可以根据配置实现动态修改表名,即将对原source table表的操作自动切换到对target table表的操作.该插件 ...

  4. 一步步教你mybatis分页,mybatis分页拦截器 使用,mybatis拦截器分页

              mybatis 分页详解.mybatis分页查询,mybatis分页拦截器使用.struts2下mybatis分页 mybatis默认是支持分页的,内部通过创建可滚动的Result ...

  5. Spring异步调用原理及SpringAop拦截器链原理

    一.Spring异步调用底层原理 开启异步调用只需一个注解@EnableAsync @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTI ...

  6. 拦截器原理多个拦截器执行顺序

    拦截器原理多个拦截器执行顺序 1.根据当前请求,找到**HandlerExecutionChain[可以处理请求的handler以及handler的所有 拦截器] 2.先来顺序执行 所有拦截器的 pr ...

  7. SpringMVC→拦截器、SpringMVC拦截器实现、多个拦截器工作原理、拦截器使用场景、拦截器Interceptor与过滤器Filter区别

    拦截器 拦截器实现 多个拦截器工作原理 拦截器使用场景 请求编码设置及请求登录Session校验 使用时间段设置 拦截器Interceptor与过滤器Filter区别

  8. 超级详细!!!SpringBoot2核心技术与响应式编程尚硅谷完整知识点笔记 下篇 自动配置、容器、Web、数据响应、拦截器、SQL、NOSQL、原理、Junit5、Actuator、外部化配置等

    所有配套资料已上传到QQ群:167356412  需要的话群文件自取 06.数据访问 1.SQL 1.数据源的自动配置-HikariDataSource 1.导入JDBC场景 <dependen ...

  9. MyBatis 分页插件 PageHelper:是如何拦截SQL进行分页

    目录 Springboot项目集成 分页插件参数介绍 如何选择配置这些参数 场景一 场景二 场景三 场景四 场景五 PageHelper的使用 PageHelper实现原理1: interceptor ...

最新文章

  1. 机器学习系列14:偏差与方差
  2. 查看mysql 内核_如何查看和更新数据库内核小版本
  3. 公众号新上线微信小游戏(疯狂猜图)
  4. 具有关联映射的Hibernate Composite ID
  5. 开发人员如何成为架构师
  6. [模拟] hdu 4452 Running Rabbits
  7. 做柱状图加数据标签_Origin绘图:如何优雅的绘制堆叠柱状图
  8. 提高测试脚本复用性降低DOM结构引起路径变化的影响
  9. C++:标准程序库-STL迭代器Iterator
  10. 【渝粤题库】陕西师范大学292111 社会学概论 作业
  11. “System.InvalidOperationException”类型的未经处理的异常在 ESRI.ArcGIS.AxControls.dll 中发生...
  12. 英伟达显卡不同架构_架构定输赢!盘点历代英伟达显卡能够成功亥市的根源
  13. 2、CSS动画之行走的米兔、奔跑的小人
  14. PDM系统与PLM系统
  15. 注册gmail账号,手机无法接受验证码的问题
  16. mysql存储表情、微信小程序存储表情
  17. Java接口的基本概念详解
  18. 相关分析怎么进行?有哪些条件?
  19. 互联网日报 | 腾讯地图上线聚合打车服务;瑞幸咖啡等公司被罚6100万元;中通快递下周二香港上市...
  20. Linux中的阻塞机制

热门文章

  1. MySQL-Btree索引和Hash索引初探
  2. 并发编程-23J.U.C组件拓展之阻塞队列BlockingQueue 和 线程池
  3. xml发生错误_WEB之web.xml详解
  4. oracle 表空间热备份,oracle对表空间的热备
  5. 2021-02-06 Python通过matplotlib包和gif包生成gif动画
  6. 2020-12-11 python查看pytorch版本
  7. 怎样在线把别人web前端代码抓下_自学web前端8个月,我是怎样拿下7K薪资的?
  8. 计算机科学与技术专业用英语怎么写,计算机科学与技术专业专业英文简历模板...
  9. java纯粹面向对象_Java的面向对象特征
  10. 【Linux】39.nslookup查看域名与其对应的ip