MyBatis Plugin 插件原理分析

1,135 阅读6分钟

参考资料:mybatis 插件原理(强烈建议先阅读一遍!!)

自定义插件

自定义插件,需要先创建一个实现org.apache.ibatis.plugin.Interceptor接口的子类,接着在配置文件中设置自定义的插件信息。

创建插件

默认情况下,MyBatis允许使用插件拦截的方法如下所示:

Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) 拦截执行器的方法;
StatementHandler (prepare, parameterize, batch, update, query) 拦截Sql语法构建的处理
ParameterHandler (getParameterObject, setParameters) 拦截参数的处理;
ResultSetHandler (handleResultSets, handleOutputParameters) 拦截结果集的处理;
@Intercepts({ // 可以拦截多个方法签名
        @Signature(
                type = Statement.class, // 可以拦截Executor、StatementHandler、ParameterHandler、ResultSetHandler
                method = "prepare",	// 被拦截的方法
                args = {Connection.class, Integer.class}
        )
})
public class MyFirstPlugin implements Interceptor {
    /**
     * 拦截方法
     *
     * @param invocation 调用信息
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("目标方法执行前。。。");
        invocation.proceed();
        System.out.println("目标方法执行后。。。。");
        return null;
    }

    /**
     * 把拦截器添加到拦截器链
     *
     * @param target 目标对象
     * @return
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * 获取配置文件的属性
     *
     * @param properties 属性
     */
    @Override
    public void setProperties(Properties properties) {
        System.out.println("插件配置的初始化参数:" + properties);
    }
}

配置插件

<plugins>
    <plugin interceptor="com.drh.MyFirstPlugin">
        <properties name="name" value="Joe"></properties>
    </plugin>
</plugins>

经过以上两个步骤,MyFirstPlugin就会拦截Statement#prepare方法,执行intercept方法。

实现原理

从配置文件解析开始分析,我们知道创建会话工厂时,会使用XMLConfigBuilder#parseConfiguration方法解析每个标签,刚刚注册插件时,使用的标签是plugins,我们跟踪下这个标签的解析。

org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration

private void parseConfiguration(XNode root) {
    try {
       
        // 解析 <plugins /> 标签
        pluginElement(root.evalNode("plugins"));
      
        ... 省略部分代码
}
/**
  * 解析 <plugins /> 标签,添加到 {@link Configuration#interceptorChain} 中
  *
  * @param parent 节点
  * @throws Exception 发生异常时
  */
prte void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
        // 遍历 <plugins /> 的子标签
        for (XNode child : parent.getChildren()) {
            String interceptor = child.getStringAttribute("interceptor");
            Properties properties = child.getChildrenAsProperties();
            // 创建 Interceptor 对象,并设置属性
            Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
            interceptorInstance.setProperties(properties);
            // 添加到拦截器链
            configuration.addInterceptor(interceptorInstance);
        }
    }
}
public void addInterceptor(Interceptor interceptor) {
    interceptorChain.addInterceptor(interceptor);
}

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

/**
 * 拦截器链
 *
 * @author Clinton Begin
 */
public class InterceptorChain {

    /**
     * 拦截器数组
     */
    private final List<Interceptor> interceptors = new ArrayList<>();

    /**
     * 应用所有插件
     *
     * @param target 目标对象
     * @return 应用结果
     */
    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、StatementHandler等接口方法,那么有可能是创建这些对象时把拦截器加进去的,以Executor为例,看下情况。

DefaultSqlSessionFactory#openSessionFromDataSource

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
       
            // 创建 Executor 对象
            final Executor executor = configuration.newExecutor(tx, execType);
    
            // 创建 DefaultSqlSession 对象
            return new DefaultSqlSession(configuration, executor, autoCommit);
    
    		... 省略部分代码
      
    }
	/**
     * 创建 Executor 对象
     *
     * @param transaction 事务对象
     * @param executorType 执行器类型
     * @return Executor 对象
     */
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
        // 获得执行器类型
        executorType = executorType == null ? defaultExecutorType : executorType; // 使用默认
        executorType = executorType == null ? ExecutorType.SIMPLE : executorType; // 使用 ExecutorType.SIMPLE
        // 创建对应实现的 Executor 对象
        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);
        }
        // 如果开启缓存,创建 CachingExecutor 对象,进行包装
        if (cacheEnabled) {
            executor = new CachingExecutor(executor);
        }
        // 调用拦截器链的pluginAll方法,目标对象插入拦截器
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
    }

在创建SqlSession时,需要先实例化Executor对象,调用configuration#newExecutor方法,该方法先通过构造方法创建Executor对象,接着调用拦截器链的pluginAll方法,估计此时返回的是执行器代理对象。

跟踪pluginAll方法,最终定位到Interceptor#plugin方法,我们找到mybatis提供的ExamplePlugin,看下它的实现

org.apache.ibatis.builder.ExamplePlugin#plugin

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

org.apache.ibatis.plugin.Plugin#wrap

/**
     * 创建目标类的代理对象
     *
     * @param target 目标类
     * @param interceptor 拦截器对象
     * @return 代理对象
     */
public static Object wrap(Object target, Interceptor interceptor) {
    // 获得拦截的方法映射
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    // 获得目标类的类型
    Class<?> type = target.getClass();
    // 获得目标类的接口集合
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    // 若有接口,则创建目标对象的 JDK Proxy 对象
    if (interfaces.length > 0) {
        // 因为 Plugin 实现了 InvocationHandler 接口,所以可以作为 JDK 动态代理的调用处理器
        return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); 
    }
    // 如果没有,则返回原始的目标对象
    return target;
}

可以看到,最终调用JDK动态代理返回Executor的代理对象。同理,如果是StatementHandler、ParameterHandler、ResultSetHandler,返回对应的代理对象。

补充其他三种类型在创建对象时,被插入拦截器的代码

// 创建 ParameterHandler 对象
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;
}

// 创建 ResultSetHandler 对象
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;
}

// 创建 StatementHandler 对象
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, 
                                            RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    // 创建 RoutingStatementHandler 对象
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, 
                                                                    parameterObject, rowBounds, resultHandler, boundSql);
    // 应用插件
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
}

代理对象执行目标方法时,会被InvocationHandler#invoke方法拦截,即org.apache.ibatis.plugin.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);
    }
}

可以看到,invoke调用的是拦截器的intercept方法,即我们实现的拦截方法。

插件相关的类

image-20201118215613319

org.apache.ibatis.plugin.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 getTarget() {
        return target;
    }

    public Method getMethod() {
        return method;
    }

    public Object[] getArgs() {
        return args;
    }

    /**
     * 调用方法
     *
     * @return 调用结果
     */
    public Object proceed() throws InvocationTargetException, IllegalAccessException {
        return method.invoke(target, args);
    }

}

org.apache.ibatis.plugin.Interceptor

public interface Interceptor {

    /**
     * 拦截方法
     *
     * @param invocation 调用信息
     * @return 调用结果
     * @throws Throwable 若发生异常
     */
    Object intercept(Invocation invocation) throws Throwable;

    /**
     * 应用插件。如应用成功,则会创建目标对象的代理对象
     *
     * @param target 目标对象
     * @return 应用的结果对象,可以是代理对象,也可以是 target 对象,也可以是任意对象。具体的,看代码实现
     */
    Object plugin(Object target);

    /**
     * 设置拦截器属性
     *
     * @param properties 属性
     */
    void setProperties(Properties properties);

}

总结

主线脉络:解析plugin标签 -> 创建代理对象 -> 拦截方法

  1. 解析plugin标签时,读取interceptor属性值,创建拦截器对象,并添加拦截器链; —— 创建会话工厂过程
  2. 创建Executor实例对象,然后调用拦截器链的pluginAll方法,执行拦截器的plugin方法,最终使用JDK动态代理,生成执行器的代理对象;—— 创建会话
  3. 代理对象执行目标方法时,被Plugin#invoke拦截,最终执行拦截器的intercept方法