MyBatis源码通~插件Plugin原理

插件Interceptor

在这里插入图片描述

  • 拦截器实现:实现Interceptor接口,完成拦截器功能。
  • 被拦截对象标记:@Intercepts+@Signature注解定义被拦截对象以及对应需要拦截的方法。(用在拦截器上)
  • 拦截器链绑定:InterceptorChain封装了所有拦截器,并为被拦截对象创建代理或者其他处理逻辑。
  • 拦截:代理对象Plugin.invoke拦截,调用拦截器的intercept方法。

0、MyBatis支持的拦截点

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

1、拦截器实现

  • Interceptor接口
//NOTE: 插件 拦截器
public interface Interceptor {
  /**
   * 拦截 逻辑处理
   * @param invocation 
   */
  Object intercept(Invocation invocation) throws Throwable;
  
  /**
   * 拦截器绑定
   * @param target 被拦截目标对象
   */
  Object plugin(Object target);

  /**
   * 属性添加
   */
  void setProperties(Properties properties);
}
  • 比如对Executor的query接口进行拦截
@Intercepts(
      @Signature(
              type = Executor.class,
              method="query",
              args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
              )
)
public class ExamplePlugin implements Interceptor {
......
}
  1. 配置:定义好拦截器后,好需要将拦截器添加到配置文件中,在初始化MyBatis时会自动加载。
  2. 触发过程:先通过 DefaultSqlSessionFactory 创建 SqlSession 。Executor 实例会在创建 SqlSession 的过程中被创建,Executor 实例创建完毕后,MyBatis 会通过 JDK 动态代理为实例生成代理类。这样,插件逻辑即可在 Executor 相关方法被调用前执行。

1.1、拦截器绑定

以Executor为例,分析拦截器是如何绑定在Executor上的?Executor实例是在开启SqlSession时被创建的:

//☆☆-DefaultSqlSessionFactory
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      ......
      //NOTE: 获取Executor对象
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    }
}

Executor 的创建过程封装在 Configuration 中,

//☆☆-Configuration
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
   ......
   //拦截器绑定
   executor = (Executor) interceptorChain.pluginAll(executor);
   return executor;
}

创建好Executor后,通过拦截器链 interceptorChain为 Executor 实例绑定拦截代理逻辑。

//☆☆InterceptorChain
public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<>();

  public Object pluginAll(Object target) {
  //遍历拦截器集合,调用拦截器的 plugin 方法植入相应的插件逻辑
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

//添加拦截器:通过解析配置文件的<plugins/>节点
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }

  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }
}

通过interceptor.plugin方法对target对象包裹一层层代理类,当在执行Executor时,执行顺序由外到内,如plugin2->plugin1->Executor。

interceptor.plugin方法只是过度,实际生成代理是调用Plugin.wrap()方法实现的。Plugin 类实现了InvocationHandler 接口,因此它可以作为参数传给 Proxy 的 newProxyInstance 方法。

//☆☆--ExamplePlugin
@Intercepts(
      @Signature(type = Executor.class, method="query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
)
public class ExamplePlugin implements Interceptor {
   @Override
    public Object plugin(Object target) {
     //调用Plugin.wrap方法
      return Plugin.wrap(target, this);
    }
}

//☆☆--Plugin
public static Object wrap(Object target, Interceptor interceptor) {
    //NOTE: 获取拦截器上定义的被拦截类和具体的方法签名信息
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);

    //NOTE: 被拦截类
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      //NOTE: JDK创建动态代理
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
}

1.2、拦截器执行

为每个被拦截对象绑定拦截器后,运行过程中的“对象”其实是一个代理,当发起方法调用时,会先触发拦截器内部逻辑,再调用被拦截对象的逻辑。

  • 拦截器的逻辑在Plugin类中,其实现InvocationHandler接口。
    • 先获取目标类是否被@Intercepts、@Signature注解,有则走拦截器逻辑;否则执行被拦截方法。
//☆☆--Plugin
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //NOTE: 获取当前方法所在类或者接口中,可被放弃Interceptor拦截的方法
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
      //NOTE: 对应方法被拦截,则调用interceptor.intercept
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //NOTE: 没有则直接走原始的方法
      return method.invoke(target, args);
    } catch (Exception e) {
     ......
    }
}

Invocation类用于封装目标类并提供一个在执行完拦截器逻辑后,回归到目标类的被拦截方法。

//☆☆--Invocation
public class Invocation {
  private final Object target;
  private final Method method;
  private final Object[] args;

  public Invocation(Object target, Method method, Object[] args) {
    this.target = target;
    this.method = method;
    this.args = args;
  }
  ......
  
  public Object proceed() throws InvocationTargetException, IllegalAccessException {
  //调用被拦截的方法,一般都是在执行完interceptor.intercept后,被调用
    return method.invoke(target, args);
  }
}

2、实现一个分页插件

实现一个插件,也就是实现Interceptor接口,具体逻辑在intercept(...)方法中。

/**
   * NOTE: 执行拦截逻辑
   * 1、通过RowBounds获取分页参数
   * 2、修改MappedStatement的BoundSql,增加limit 分页
   * 3、调用执行方法
   */
  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    //获取query方法中的RowBounds参数
    RowBounds rowBounds = (RowBounds) args[2];
    if (rowBounds.equals(RowBounds.DEFAULT)) {
      // 无需分页
      return invocation.proceed();
    }

    //将原 RowBounds 参数设为 RowBounds.DEFAULT,关闭 MyBatis 内置的分页机制
    args[2] = RowBounds.DEFAULT;

    //获取query方法中的MappedStatement参数和传入参数
    MappedStatement mappedStatements = (MappedStatement) args[0];
    Object params = args[1];


    BoundSql boundSql = mappedStatements.getBoundSql(params);

    //获取Sql并增加分页limit
    String sql = boundSql.getSql();
    String limit = String.format("limit %s, %s", rowBounds.getOffset(), rowBounds.getLimit());
    sql = sql + " " + limit;


    //将新的sql重新塞会MappedStatement -- SqlSource
    SqlSource sqlSource = new StaticSqlSource(mappedStatements.getConfiguration(), sql, boundSql.getParameterMappings());

    //☆☆-重置MappedStatement的sqlSource

    // 方式1:通过反射获取并设置 MappedStatement 的 sqlSource 字段
    Field field = MappedStatement.class.getDeclaredField("sqlSource");
    field.setAccessible(true);
    field.set(mappedStatements, sqlSource);
    
    //方式2:通过MyBatis内部的反射模块实现
     MetaObject metaObject = SystemMetaObject.forObject(mappedStatements);
    metaObject.setValue("sqlSource", sqlSource);
    

    //调用被拦截方法
    return invocation.proceed();
}

通过获取Executor.query方法的三个参数,对SQL执行的所有信息进行修改,主要思路:

  • 获取RowBounds参数,获取分页的信息,若配置不需要分页RowBounds.DEFAULT,则直接调用被拦截方法,否则将传入的RowBounds设置为RowBounds.DEFAULT来关闭MyBatis内置的分页机制;
  • 获取MappedStatement参数以及BoundSql,得到原生的sql语句,再集合RowBounds参数拼接处新的sql语句;
  • 重新创建SqlSource并通过反射重置MappedStatement的sqlSource属性,完成插件逻辑。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只打杂的码农

你的鼓励是对我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值