MyBatis配置项--插件(plugins)

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

·Executor(update,query,flushStatement,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,

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

  }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<!-- mybatis-config.xml -->

<plugins>

  <plugin interceptor="org.mybatis.example.ExamplePlugin">

    <property name="someProperty" value="100"/>

  </plugin>

</plugins>

 

 

 

 

 

 

 

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

提示:覆盖配置类

除了用插件来修改MyBatis核心行为之外,还可以通过完全覆盖配置类来达到目的。

只需继承后覆盖其中的每个方法,再把它传递到SqlSessionFactoryBuilder.build(myConfig)方法即可。

再次重申,这可能会严重影响MyBatis的行为,请慎重。

 

posted on 2019-01-31 15:15  arrows  阅读(338)  评论(0编辑  收藏  举报

导航