广告
返回顶部
首页 > 资讯 > 后端开发 > Python >mybatis-plugin插件执行原理解析
  • 526
分享到

mybatis-plugin插件执行原理解析

mybatis-plugin插件mybatis-plugin插件原理 2022-11-13 18:11:45 526人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

mybatis-plugin插件执行原理 今天主要是在看mybatis的主流程源码,其中比较感兴趣的是mybatis的plugin功能,这里主要记录下mybatis-plugin的插

mybatis-plugin插件执行原理

今天主要是在看mybatis的主流程源码,其中比较感兴趣的是mybatis的plugin功能,这里主要记录下mybatis-plugin的插件功能原理。

plugin集合列表:在构建sqlSessionFactory时,通过解析配置或者plugin-bean的注入,会将所有的mybatis-plugin都收集到Configuration
对象的interceptorChain属性中。InterceptorChain类定义如下:

public class InterceptorChain {

  private final List<Interceptor> 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<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

plugin作用对象:Executor,ParameterHandler,ResultSetHandler,StatementHandler,这4个对象在mybatis执行sql的过程中
有不同的作用。

Executor:sql执行的具体操作对象。
ParameterHandler:sql执行前的参数处理对象。
ResultSetHandler:sql执行后的结果集处理对象。
StatementHandler:具体送到数据库执行的sql操作对象。

plugin作用原理:类似aop,使用jdk动态代理,只不过mybatis的增强对象不是所有对象,而是上面陈列的4个对象而已。
在4个对象创建时,都会对各个对象进行判断,是否需要进行插件化。比如下面的插件:

@Intercepts({@Signature( type= Executor.class,  method = "query", args ={
        MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
})})
    public class ExamplePlugin implements Interceptor {

    //  分页   读写分离    Select  增删改

        public Object intercept(Invocation invocation) throws Throwable {
            System.out.println("代理");
        Object[] args = invocation.getArgs();
        MappedStatement ms= (MappedStatement) args[0];
        // 执行下一个拦截器、直到尽头
        return invocation.proceed();
    }
}

该插件将会在Executor该对象创建时,使用该插件进行增强。在新开一个sqlSession时,将会创建Executor对象。跟踪到具体方法:

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    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 {
      //简单的sql执行器对象
      executor = new SimpleExecutor(this, transaction);
    }
    //判断mybatis的全局配置文件是否开启缓存
    if (cacheEnabled) {
      //把当前的简单的执行器包装成一个CachingExecutor
      executor = new CachingExecutor(executor);
    }
    
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

我们找到interceptorChain.pluginAll方法:

public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

发现会通过已加载的所有plugin列表中,逐个遍历去筛选出符合Executor类型的插件,再通过具体插件的interceptor.plugin方法去创建
Executor的代理对象。

public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }
  default void setProperties(Properties properties) {
    // NOP
  }
}

再看到具体的Plugin.wrap(target, this)方法:

  public static Object wrap(Object target, Interceptor interceptor) {
    // 获得interceptor配置的@Signature的type
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    // 当前代理类型
    Class<?> type = target.getClass();
    // 根据当前代理类型 和 @signature指定的type进行配对, 配对成功则可以代理
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

这里我们就很清楚了,通过@Signature注解上的type、method、args属性去匹配,如果找到符合的,就会为对象创建代理对象,并返回代理对象。

责任链设计模式:因为一个增强对象可能会有多个plugin的增强逻辑,所以在执行的时候使用的是责任链设计模式。

因为Plugin.wrap()方法新建的代理对象中使用的InvocationHandler对象是Plugin本身,所以在执行方法的时候首先要调用它的invoke方法,

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

当我们执行Executor的query方法时,符合if (methods != null && methods.contains(method)) {条件,这时就会去执行具体插件的增强方法,interceptor.intercept
然后再通过传递new Invocation(target, method, args)对象,在插件执行完之后,再调用invocation.proceed()去执行下一个插件逻辑。
如下是对Executor的query方法添加了2个插件的场景:

总结:如果我们的业务需要我们去编写sql插件,那我们就需要来研究下Executor,ParameterHandler,ResultSetHandler,StatementHandler这4个对象的具体跟sql相关的方法,
然后再进行修改,就可以直接起到aop的作用。

到此这篇关于mybatis-plugin插件执行原理的文章就介绍到这了,更多相关mybatis-plugin插件内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: mybatis-plugin插件执行原理解析

本文链接: https://www.lsjlt.com/news/169660.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作