Mybatis Plugin 插件(拦截器)原理分析

Mybatis Plugin 插件(拦截器)原理分析

引言

最近在看mybatis 源码,看到了mybatis plugin部分,其实就是利用JDK动态代理和责任链设计模式的综合运用。采用责任链模式,通过动态代理组织多个拦截器,通过这些拦截器你可以做一些你想做的事。具体分析从一个普通的需求功能开始:现在要对所有的接口方法做一个日志记录和接口耗时记录。

需求分析和功能实现

看到这个需求功能我默默的笑了,这还不简单,每个方法我都加上不就行了吗?就这么干,撸起袖子开始噼噼啪啪的敲打着键盘,慢慢发现太特么多方法了,而且还是基本重复的,这样写下去不是办法啊。这么多重复的是不是可以抽取出来呢,要坚持 DRY(Don't repeat yourself)原则。这时候想到了代理设计模式,静态代理模式肯定不行,这么多接口,得写多少个代理类啊,还是用JDK的动态代理吧

JDK动态代理

public interface Target {
    String execute(String name);
}

public class TargetImpl implements Target {
    @Override
    public String execute(String name) {
        System.out.println("execute() "+ name);
        return name;
    }
}

public class TargetProxy implements InvocationHandler {

    private Object target;
    public TargetProxy(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(" 拦截前。。。");
        Object result = method.invoke(target, args);
        System.out.println(" 拦截后。。。");
        return result;
    }

    public static Object wrap(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),new TargetProxy(target));
    }
}

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        //返回的是代理对象,实现了Target接口,
        //实际调用方法的时候,是调用TargetProxy的invoke()方法
        Target targetProxy = (Target) TargetProxy.wrap(target);
        targetProxy.execute(" HelloWord ");

    }
}

TargetProxy.wrap(target) 实际返回的对象类似下面这样,这样看起来就容易理解点了

public class $Proxy implements Target {

    private InvocationHandler targetProxy
    
    @Override
    public String execute(String name) {
        return targetProxy.invoke();
    }
}

运行结果:

拦截前。。。
execute()  HelloWord 
 拦截后。。。

嗯,这思路是正确的了。但还是存在问题,execute() 是业务代码,我把所有的要拦截处理的逻辑都写到invoke方法里面了,不符合面向对象的思想,可以抽象一下处理。可以设计一个Interceptor接口,需要做什么拦截处理实现接口就行了。

public interface Interceptor {
    /**
     * 具体拦截处理
     */
    void intercept();

}

intercept() 方法就可以处理各种前期准备了

public class LogInterceptor implements Interceptor {

    @Override
    public void intercept() {
        System.out.println(" 记录日志 ");
    }
}

public class TransactionInterceptor implements Interceptor {

    @Override
    public void intercept() {
        System.out.println(" 开启事务 ");
    }
}

代理对象也做一下修改

public class TargetProxy implements InvocationHandler {

    private Object target;

    private List interceptorList = new ArrayList<>();

    public TargetProxy(Object target,List interceptorList) {
        this.target = target;
        this.interceptorList = interceptorList;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        /**
         *  处理拦截
         */
        for (Interceptor interceptor : interceptorList) {
            interceptor.intercept();
        }
        return method.invoke(target, args);
    }

    public static Object wrap(Object target,List interceptorList) {
        TargetProxy targetProxy = new TargetProxy(target, interceptorList);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                                      target.getClass().getInterfaces(),targetProxy);
    }
}

现在可以根据需要动态的添加拦截器了,在每次执行业务代码execute(...)之前都会拦截,看起来高级一丢丢了,来测试一下

public class Test {

    public static void main(String[] args) {

        List interceptorList = new ArrayList<>();
        interceptorList.add(new LogInterceptor());
        interceptorList.add(new TransactionInterceptor());

        Target target = new TargetImpl();
        Target targetProxy = (Target) TargetProxy.wrap(target,interceptorList);
        targetProxy.execute(" HelloWord ");

    }
}

执行结果:

 记录日志 
 开启事务 
execute()  HelloWord 

貌似有哪里不太对一样,按照上面这种我们只能做前置拦截,而且拦截器并不知道拦截对象的信息。应该做更一步的抽象,把拦截对象信息进行封装,作为拦截器拦截方法的参数,把拦截目标对象真正的执行方法放到Interceptor中完成,这样就可以实现前后拦截,并且还能对拦截对象的参数等做修改。设计一个Invocation 对象

public class Invocation {

    /**
     * 目标对象
     */
    private Object target;
    /**
     * 执行的方法
     */
    private Method method;
    /**
     * 方法的参数
     */
    private Object[] args;
    
    //省略getset

    public Invocation(Object target, Method method, Object[] args) {
        this.target = target;
        this.method = method;
        this.args = args;
    }

    /**
     * 执行目标对象的方法
     * @return
     * @throws Exception
     */
    public Object process() throws Exception{
       return method.invoke(target,args);
    }
}

拦截接口做修改

public interface Interceptor {
    /**
     * 具体拦截处理
     * @param invocation
     * @return
     * @throws Exception
     */
    Object intercept(Invocation invocation) throws Exception;

}

Invocation 类就是被代理对象的封装,也就是要拦截的真正对象。TargetProxy修改如下:

public class TargetProxy implements InvocationHandler {

    private Object target;

    private Interceptor interceptor;

    public TargetProxy(Object target,Interceptor interceptor) {
        this.target = target;
        this.interceptor = interceptor;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Invocation invocation = new Invocation(target,method,args);
        return interceptor.intercept(invocation);
    }

    public static Object wrap(Object target,Interceptor interceptor) {
        TargetProxy targetProxy = new TargetProxy(target, interceptor);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),targetProxy);
    }
}
public class TransactionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Exception{
        System.out.println(" 开启事务 ");
        Object result = invocation.process();
        System.out.println(" 提交事务 ");
        return result;
    }
}

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        Target targetProxy = (Target) TargetProxy.wrap(target,transactionInterceptor);
        targetProxy.execute(" HelloWord ");

    }
}

运行结果:

 开启事务 
execute()  HelloWord 
  提交事务 

这样就能实现前后拦截,并且拦截器能获取拦截对象信息,这样扩展性就好很多了。但是测试例子的这样调用看着很别扭,对应目标类来说,只需要了解对他插入了什么拦截就好。再修改一下,在拦截器增加一个插入目标类的方法

public interface Interceptor {
    /**
     * 具体拦截处理
     * @param invocation
     * @return
     * @throws Exception
     */
    Object intercept(Invocation invocation) throws Exception;

    /**
     *  插入目标类
     * @param target
     * @return
     */
    Object plugin(Object target);

}

public class TransactionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Exception{
        System.out.println(" 开启事务 ");
        Object result = invocation.process();
        System.out.println(" 提交事务 ");
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return TargetProxy.wrap(target,this);
    }
}

这样目标类仅仅需要在执行前,插入需要的拦截器就好了,测试代码:

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        //把事务拦截器插入到目标类中
        target = (Target) transactionInterceptor.plugin(target);
        target.execute(" HelloWord ");

    }
}

运行结果:

 开启事务 
execute()  HelloWord 
 提交事务 

到这里就差不多完成了,可能有同学可能会有疑问,那我要添加多个拦截器呢,怎么搞?

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        target = (Target) transactionInterceptor.plugin(target);
        LogInterceptor logInterceptor = new LogInterceptor();
        target = (Target)logInterceptor.plugin(target);
        target.execute(" HelloWord ");

    }
}

运行结果:

 开始记录日志 
 开启事务 
execute()  HelloWord 
 提交事务 
 结束记录日志 

其实这就是代理嵌套再代理,下图是执行的时序图,每个步骤就不做详细的说明了

Mybatis Plugin 插件(拦截器)原理分析_第1张图片
时序图.png

责任链

其实上面已经实现的没问题了,只是还差那么一点点,添加多个拦截器的时候不太美观,让我们再次利用面向对象思想封装一下。我们设计一个InterceptorChain 拦截器链类

public class InterceptorChain {

    private List interceptorList = new ArrayList<>();

    /**
     * 插入所有拦截器
     * @param target
     * @return
     */
    public Object pluginAll(Object target) {
        for (Interceptor interceptor : interceptorList) {
            target = interceptor.plugin(target);
        }
        return target;
    }

    public void addInterceptor(Interceptor interceptor) {
        interceptorList.add(interceptor);
    }

    /**
     * 返回一个不可修改集合,只能通过addInterceptor方法添加
     * 这样控制权就在自己手里
     * @return
     */
    public List getInterceptorList() {
        return Collections.unmodifiableList(interceptorList);
    }


}

其实就是通过pluginAll() 方法包一层把所有的拦截器插入到目标类去而已。测试代码:

public class Test {

    public static void main(String[] args) {

        Target target = new TargetImpl();
        Interceptor transactionInterceptor = new TransactionInterceptor();
        LogInterceptor logInterceptor = new LogInterceptor();
        InterceptorChain interceptorChain = new InterceptorChain();
        interceptorChain.addInterceptor(transactionInterceptor);
        interceptorChain.addInterceptor(logInterceptor);
        target = (Target) interceptorChain.pluginAll(target);
        target.execute(" HelloWord ");

    }
}

Mybatis Plugin 插件分析

经过上面的分析,再去看mybastis plugin 源码的时候就很轻松了。

Mybatis Plugin 插件(拦截器)原理分析_第2张图片
mybatis-plugin代码图

有没有觉得似曾相似的感觉呢,没错你的感觉是对的,这基本和我们上面的最终实现是一致的,Plugin 相当于我们的TargetProxy。

Mybatis Plugin 介绍及配置使用

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis允许使用插件来拦截的方法调用包括:

1.Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) 拦截执行器的方法;
2.ParameterHandler (getParameterObject, setParameters) 拦截参数的处理;
3.ResultSetHandler (handleResultSets, handleOutputParameters) 拦截结果集的处理;
4.StatementHandler (prepare, parameterize, batch, update, query) 拦截Sql语法构建的处理

参考Mybatis 官方的一个例子:

  1. 在全局配置文件mybatis-config.xml 添加

    
        
    
    
  2. 写好拦截类代码

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

    这个拦截器会拦截Executor接口的update方法

源码简要分析

首先从配置文件解析开始

public class XMLConfigBuilder extends BaseBuilder {
    //解析配置
  private void parseConfiguration(XNode root) {
    try {
     //省略部分代码
      pluginElement(root.evalNode("plugins"));
     
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }
    
   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);
        //调用InterceptorChain.addInterceptor
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }
}

上面的代码主要是解析配置文件的plugin节点,根据配置的interceptor 属性实例化Interceptor 对象,然后添加到Configuration 对象中的InterceptorChain 属性中

public class InterceptorChain {


  private final List interceptors = new ArrayList();

  public Object pluginAll(Object target) {
    //循环调用每个Interceptor.plugin方法
    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);
  }

}

这个就和我们上面实现的是一样的。定义了拦截器链,初始化配置文件的时候就把所有的拦截器添加到拦截器链中,下面来看一下什么时候把拦截器插入到需要拦截的接口中

public class Configuration {

    protected final InterceptorChain interceptorChain = new InterceptorChain();
    //创建参数处理器
  public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    //创建ParameterHandler
    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) {
    //创建DefaultResultSetHandler
    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) {
    return newExecutor(transaction, defaultExecutorType);
  }

  //产生执行器
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    //这句再做一下保护,囧,防止粗心大意的人将defaultExecutorType设成null?
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    //然后就是简单的3个分支,产生3种执行器BatchExecutor/ReuseExecutor/SimpleExecutor
    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);
    }
    //如果要求缓存,生成另一种CachingExecutor(默认就是有缓存),装饰者模式,所以默认都是返回CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    //此处调用插件,通过插件可以改变Executor行为
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
}

从代码可以看出mybatis 在实例化Executor、ParameterHandler、ResultSetHandler、StatementHandler四大接口对象的时候调用interceptorChain.pluginAll() 方法插入进去的。其实就是循环执行拦截器链所有的拦截器的plugin() 方法,mybatis官方推荐的plugin方法是Plugin.wrap() 方法,这个类就是我们上面的TargetProxy类

public class Plugin implements InvocationHandler {

    public static Object wrap(Object target, Interceptor interceptor) {
    //从拦截器的注解中获取拦截的类名和方法信息
    Map, Set> signatureMap = getSignatureMap(interceptor);
    //取得要改变行为的类(ParameterHandler|ResultSetHandler|StatementHandler|Executor)
    Class type = target.getClass();
    //取得接口
    Class[] interfaces = getAllInterfaces(type, signatureMap);
    //产生代理,是Interceptor注解的接口的实现类才会产生代理
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
    
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //获取需要拦截的方法
      Set methods = signatureMap.get(method.getDeclaringClass());
      //是Interceptor实现类注解的方法才会拦截处理
      if (methods != null && methods.contains(method)) {
        //调用Interceptor.intercept,也即插入了我们自己的逻辑
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //最后还是执行原来逻辑
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
    
    //取得签名Map,就是获取Interceptor实现类上面的注解,要拦截的是那个类(Executor,ParameterHandler,   ResultSetHandler,StatementHandler)的那个方法
  private static Map, Set> getSignatureMap(Interceptor interceptor) {
    //取Intercepts注解,例子可参见ExamplePlugin.java
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    //必须得有Intercepts注解,没有报错
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    //value是数组型,Signature的数组
    Signature[] sigs = interceptsAnnotation.value();
    //每个class里有多个Method需要被拦截,所以这么定义
    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;
  }
    
    //取得接口
  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()]);
  }
}
总结

Mybatis 拦截器的使用是实现Interceptor接口

public interface Interceptor {

  //拦截
  Object intercept(Invocation invocation) throws Throwable;

  //插入
  Object plugin(Object target);

  //设置属性(扩展)
  void setProperties(Properties properties);

}

通过上面的分析可以知道,所有可能被拦截的处理类都会生成一个代理类,如果有N个拦截器,就会有N个代理,层层生成动态代理是比较耗性能的。而且虽然能指定插件拦截的位置,但这个是在执行方法时利用反射动态判断的,初始化的时候就是简单的把拦截器插入到了所有可以拦截的地方。所以尽量不要编写不必要的拦截器。

你可能感兴趣的:(Mybatis Plugin 插件(拦截器)原理分析)