插件(plugins)配置

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

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 MyBatis 发行包中的源代码。 如果你想做的不仅仅是监控方法的调用,那么你最好相当了解要重写的方法的行为。 因为如果在试图修改或重写已有方法的行为的时候,你很可能在破坏 MyBatis 的核心模块。 这些都是更低层的类和方法,所以使用插件的时候要特别当心。

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

ExamplePlugin.java

@Intercepts({@Signature(
  type= Executor.class,//标记需要拦截的类,只能是: StatementHandler | ParameterHandler | ResultSetHandler | Executor 类或者子类
  method = "update",// 标记是拦截类的那个方法,表示:拦截Executor的update方法
  args = {MappedStatement.class,Object.class})})// 指定拦截方法的参数列表(update方法可能有重载)
public class ExamplePlugin implements Interceptor {
  /**
     * 具体拦截的实现逻辑
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("----------- 开始拦截到 update 方法.... ---------");
        //调用被拦截的方法
        Object result = invocation.proceed();
        System.out.println("----------- 结束拦截 update 方法.... ---------");
        return result;
    }

    /**
     * 加载插件,
     * @param o
     * @return
     */
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);//一般使用 Plugin.wrap(o, this);加载当前插件
    }

    /**
     * 初始化属性
     * @param properties
     */
    @Override
    public void setProperties(Properties properties) {
        System.out.println("接受到参数了:" + properties.getProperty("someProperty"));
    }
}

mybatis-config.xml

<plugins>
  <plugin interceptor="org.mybatis.example.ExamplePlugin">
    <property name="someProperty" value="110"/>
  </plugin>
</plugins>

上面的插件将会拦截在 Executor 实例中所有的 “update(MappedStatement var1, Object var2)” 方法调用, 这里的 Executor 是负责执行低层映射语句的内部对象。

提示:

​ 除了用插件来修改 MyBatis 核心行为之外,还可以通过完全覆盖配置类来达到目的。只需继承后覆盖其中的每个方法,再把它传递到 SqlSessionFactoryBuilder.build(myConfig) 方法即可。再次重申,这可能会严重影响 MyBatis 的行为,务请慎之又慎。

results matching ""

    No results matching ""