Mybatis 的插件系统

781 阅读6分钟

什么是插件?

插件是一种遵循一定规范的应用程序接口编写出来的程序,其只能运行在程序规定的系统平台下,而不能脱离指定的平台单独运行。

插件必须依赖于应用程序才能发挥自身功能,仅靠插件是无法正常运行的。相反地,应用程序并不需要依赖插件就可以运行,这样一来,插件就可以加载到应用程序上并且动态更新而不会对应用程序造成任何改变。

Mybatis 中的插件

Mybatis 中提供了一套插件系统供开发者使用,以便其能介入 Mybatis 的运行。例如比较出名的 Mybatis 分页插件 Mybatis-PageHelper 就是利用 Mybatis 提供的插件机制来实现的。

通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。

@Intercepts({@Signature(
  type= Executor.class,
  method = "query",
  args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class ExamplePlugin implements Interceptor {
  
  public Object intercept(Invocation invocation) throws Throwable {
    // implement pre processing if need
    Object returnObject = invocation.proceed();
    // implement post processing if need
    return returnObject;
  }
}

编写好插件之后,就可以在配置文件进行配置。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置插件 -->
    <plugins>
        <plugin interceptor="ExamplePlugin"/>
    </plugins>
    <mappers>
        <mapper resource="mapper/Test.xml"/>
    </mappers>
</configuration>

Mybatis 如何获取插件

Mybatis 获取插件的方式很简单,因为已经在 XML 配置文件中指定了插件的全限定类名,只需要根据全限定类名去获取插件类即可。

// 已经获取了 <plugins> 元素
private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
        // 循环获取 <plugin> 元素
        for (XNode child : parent.getChildren()) {
            // 获取 interceptor 属性,也就是全限定类名/别名
            String interceptor = child.getStringAttribute("interceptor");
            Properties properties = child.getChildrenAsProperties();
            Interceptor interceptorInstance = (Interceptor)resolveClass(interceptor).getDeclaredConstructor().newInstance();
            interceptorInstance.setProperties(properties);
            // 将插件添加到全局配置类中。
            configuration.addInterceptor(interceptorInstance);
        }
    }
}

resolveClass(interceptor) 该方法的主要作用是根据别名查询真正的类,所以我们不一定要直接写插件的全限定类名,也可以写它的别名。

得到真正的类时,通过反射创建该类的对象,并将它放入到全局配置当中。

public void addInterceptor(Interceptor interceptor) {
    interceptorChain.addInterceptor(interceptor);
}
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);
    }

}

我们通过源码可以看到,它是将插件对象放入到 InterceptorChain 中,而 InterceptorChain 中通过一个集合进行存储。

Mybatis 从配置文件获取插件流程.jpg

Mybatis 如何配置插件

Mybatis 在获取完插件之后,那么就需要进行配置了,将其设置到执行的地方,等待被使用。

我们根据文档可以知道,Mybatis 允许使用插件拦截以下方法:

接口ExecutorParameterHandlerResultSetHandlerStatementHandler
updategetParameterObjecthandleResultSetsprepare
querysetParametershandleOutputParametersparameterize
flushStatementsbatch
commitupdate
rollbackquery
getTransaction
close
isClosed

我们通常看到拦截方法的执行,那么就可以想到使用了动态代理,所以我们需要找出哪个地方对这四个类型的类进行代理,通过阅读代码,可以找到下面的代码对 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 {
        executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
        executor = new CachingExecutor(executor);
    }
    // 这句语句,对新建的执行器 executor 进行了一个跟插件有关的操作。
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

我们可以看到第 16 行语句,它执行了 InterceptorChain 对象的 pluginAll 方法,以刚创建出来的执行器 Executor 作为参数,所以,我们可以猜测,这里面对执行器对象做了一些操作,这些操作可以拦截指定的方法。

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

}

pluginAll 方法将上一步获取到的插件,循环执行它们的 plugin 方法,以 Executor 为参数,这个方法是 Interceptor 接口的一个默认方法。

default Object plugin(Object target) {
    return Plugin.wrap(target, this);
}
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;
}
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;
}
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> 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()]);
}
  1. 先执行 getSignatureMap 方法解析 Interceptor 接口上的 Intercepts 注解,获取注解上表明的需要拦截的类和方法,将它们以 Map 的形式包装。
  2. 执行 getAllInterfaces ,判断是否存在可用的接口。先获取 Executor 上的接口,如果 signatureMap 中包含这些接口,则将这些接口返回。
  3. 创建一个 Plugin 为代理类的代理对象,其中代理对象实现了上一步中获取的接口。

所以,最后面拿到的是一个代理对象,这个代理对象实现了需要拦截的接口。假设这里使用 SimpleExecutor,该类实现了 Executor 接口,并且根据文章开头的例子,表示需要拦截的方法是 Executor 接口中的 query 方法。最后创建代理对象的实际方法如下:

Proxy.newProxyInstance(
    type.getClassLoader(),
    Class[]{Executor.class},
    new Plugin(simpleExecutor, interceptor, signatureMap));

Mybatis 配置插件流程.jpg

Mybatis 如何使用插件

通过上面的分析,我们知道,在创建执行器 Executor 的时候,如果存在插件的话,那么返回的就是一个 Plugin 代理对象,而不是一个原始的执行器对象。

所以在执行相关方法时,就会对其进行拦截。在例子中,我们指定插件需要为我们拦截 Executorquery(MapperStatement ms, Object args, RowBounds rb, ResultHandler rh)

所以,在执行该方法的时候,就会进入到代理对象的 invoke 方法。

// DefaultSqlSession.class
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
        MappedStatement ms = configuration.getMappedStatement(statement);
        return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
        throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
        ErrorContext.instance().reset();
    }
}

selectList 中执行了 Executor 对象的 query 方法。此时它进入到代理对象 Plugininvoke 方法。

// Plugin.class
@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 中的所有被拦截的方法,也就是被 @Signature 注解的方法,然后查询这些方法中是否存在与被执行的方法相同的方法,如果存在,则表示现在执行的方法需要被拦截,那么此时就需要执行插件中的 intercept 方法。

嵌套的代理对象

如果我们有多个插件,那么 Mybatis 会怎么处理呢?

我们通过看下面这段代码就可以知道,它是将每一个代理对象进行嵌套了。

public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
        target = interceptor.plugin(target);
    }
    return target;
}

如果我们有三个插件:ExamplePlugin1ExamplePlugin2ExamplePlugin3

Mybatis 嵌套代理对象.jpg

这里的执行顺序就是 ExamplePlugin3 -> ExamplePlugin2 -> ExamplePlugin1 -> Executor。

这个顺序是根据 Mybatis 获取到的插件顺序来嵌套的,所以,如果插件之间如果有顺序,那么则要小心处理,因为它可能不会按照你预期的顺序进行处理。