mybatis 源码分析(三) 拦截器原理

mybatis 源码分析(三) 插件原理


在使用mybatis过程中 我们可能需要对sql 产生的构建的中间环节 进行一些特殊处理
(比如 更换主从库连接 自定义分表操作 ….) 这个时候就需要使用到拦截器

Interceptor 官方文档

/**
 * @author Clinton Begin
 */
public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  Object plugin(Object target);

  void setProperties(Properties properties);

}

在第一章中 已经指明
plugins 插件配置 是 注入到 SqlSessionFactoryBean 实例中的

SqlSessionFactoryBean

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {

    protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
    /** 省略其他代码 */
        if (!isEmpty(this.plugins)) {
      for (Interceptor plugin : this.plugins) {
        /** 配置类中添加插件实现 往下跟踪会到 InterceptorChain*/
        configuration.addInterceptor(plugin);
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("Registered plugin: '" + plugin + "'");
        }
      }
    }
 }
}

InterceptorChain

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

那么拦截器是在什么地方使用的呢?
第一章的 DefaultSqlSessionFactory 的 第21行代码 创建executor

Configuration

public class Configuration {
  /** 省略其他代码 */
  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 {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    /** 使用动态代理包装了executor */
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
}

由于 interceptorChain.pluginAll 实际上是循环调用interceptor的plugin方法
所以 我们根据官网提供的代码 继续分析
如果搜索下 就会发现 interceptor 在4个地方进行了代理拦截
这里写图片描述

ExamplePlugin

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

Plugin

public class Plugin implements InvocationHandler {

  private Object target;
  private Interceptor interceptor;
  private Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  public static Object wrap(Object target, Interceptor interceptor) {
    /**
     * 该方法是解析拦截器实现类上面的 Intercepts 注解
     * 标明executor中那些方法需要被拦截
     */
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    /** 代理 org.apache.ibatis.executor.Executor 接口
      * Plugin 实现了动态代理接口 所以调用 Executor 任何方法
      * 都会进入到 invoke里面
      */
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

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

  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    //TO DO
    return signatureMap;
  }

  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    //TO DO
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }

}

看完之后是不是觉得 拦截器 就是不停的对 上一个 动态代理的Executor 在包装一层动态代理类!!!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值