Mybatis源码解析7:拦截器Interceptor

Mybatis源码解析7:拦截器Interceptor

    • 1.项目结构
    • 2. 源码分析
      • 2.1 解析plugins标签
      • 2.2 创建对象 Configuration#newStatementHandler
      • 2.3 注册插件 InterceptorChain#pluginAll
      • 2.4 拦截器包装 Plugin#wrap
        • 2.4.1 解析Intercepts和Signature Plugin#getSignatureMap
        • 2.4.2 拦截器回调 Plugin#invoke

1.项目结构

  1. mybatis拦截器是基于JDK动态代理实现的
  2. 就拿StatementHandler拦截器举例
<plugins>
    <plugin interceptor="com.lmh.mybatis.plugin.interceptor.MyInterceptor"/>
 plugins>
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})})
public class MyInterceptor implements Interceptor {

    /**
     * 拦截器调用执行的逻辑
     */
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("Process interceptor for doQuery method ...");
        return invocation.proceed();
    }

    /**
     * 注册拦截器,父类已注册
     */
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * 设置属性
     */
    public void setProperties(Properties properties) {

    }

}

2. 源码分析

2.1 解析plugins标签

在SqlSessionFactoryBuilder解析mybatis-config.xml的时候,会通过XmlConfigBuilder对plugin标签进行解析

XMLConfigBuilder#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).getDeclaredConstructor().newInstance();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
}
  1. 获取plugin节点的interceptor属性,实例化Interceptor。plugin标签里面还可以配置property标签,为Interceptor属性
  2. 将拦截器注册到拦截器链Configuration#interceptorChain,interceptorChain内部维护了一个List存放Interceptor
  3. 在启动的时候,就已经对拦截器进行了注册

2.2 创建对象 Configuration#newStatementHandler

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

创建RoutingStatementHandler,通过拦截器链进行插件化

2.3 注册插件 InterceptorChain#pluginAll

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

}

遍历interceptor,调用plugin方法。而我们自定义的拦截器,一般都是通过Plugin#wrap对interceptor进行封装。

2.4 拦截器包装 Plugin#wrap

public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> 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;
}
  1. 参数:target为要被代理的对象,也就是CachingStatementHandler对象, interceptor为当前定义的拦截器
  2. 获取签名,也就是解析@Intercepts和@Signature注解。返回的key为表示需要代理的类型(StatementHandler), value为需要代理的方法(query)。
  3. 获取到当前对象CachingStatementHandler的所有接口,然后进行JDK代理
  4. 代理拦截器为Plugin,会将签名signatureMap给到Plugin,方便invoke的时候校验方法是否被代理
2.4.1 解析Intercepts和Signature Plugin#getSignatureMap
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
      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;
  }
  1. 获取定义的拦截器Interceptor类上面的Intercepts注解,一个Intercepts注解里面对应多个Signature注解
  2. 遍历Signature,通过需要被代理的类型(StatementHandler),还有方法名称(query),参数类型({Statement.class, ResultHandler.class}),反射获取到method对象
2.4.2 拦截器回调 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);
    }
  }
  1. Plugin实现了InvocationHandler接口,上面我们已经对StatementHandler接口进行了代理,所以在调用任何方法的时候,StatementHandlerCaching都会回调Plugin#invoke
  2. 通过signatureMap判断了当前调用的方法是否需要被拦截。如果不需要被拦截,就直接回调该方法;如果需要被拦截,那么就调用interceptor#intercept,其中会把当前的对象,方法,参数都封装到了Invocation对象里面,供拦截器消费

最后,拦截器的注册,消费流程都已经完成了。值得注意的是,在interceptor方法里面可以写自己的逻辑。可通过invocation.proceed()方法继续执行(在多重嵌套代理的情况下,不会直接返回,会继续回调下一个代理对象的方法)

你可能感兴趣的:(mybatis,java,sql)