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);     }     /**      * TODO:调用所有的拦截器对象plugin方法      * 插件: 责任链+ 装饰器模式(动态代理)      */     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的增强逻辑,所以在执行的时候使用的是责任链设计模式。
mybatis-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个插件的场景:
mybatis-plugin插件执行原理

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

发表评论

评论已关闭。

相关文章