插件(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 接口,并指定想要拦截的方法签名即可。

  1. // ExamplePlugin.java
  2. @Intercepts({@Signature(
  3. type= Executor.class,
  4. method = "update",
  5. args = {MappedStatement.class,Object.class})})
  6. public class ExamplePlugin implements Interceptor {
  7. private Properties properties = new Properties();
  8. public Object intercept(Invocation invocation) throws Throwable {
  9. // implement pre processing if need
  10. Object returnObject = invocation.proceed();
  11. // implement post processing if need
  12. return returnObject;
  13. }
  14. public void setProperties(Properties properties) {
  15. this.properties = properties;
  16. }
  17. }
  1. <!-- mybatis-config.xml -->
  2. <plugins>
  3. <plugin interceptor="org.mybatis.example.ExamplePlugin">
  4. <property name="someProperty" value="100"/>
  5. </plugin>
  6. </plugins>

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

提示 覆盖配置类

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