官方说明:html
MyBatis 容许你在已映射语句执行过程当中的某一点进行拦截调用。java
什么意思呢?就是你能够对执行某些方法以前进行拦截,作本身的一些操做,如:sql
1.记录全部执行的SQL(经过对 MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法进行拦截)apache
2.修改SQL(org.apache.ibatis.executor.Executor中query方法进行拦截)等。mybatis
但拦截的方法调用有限制,MyBatis 容许使用插件来拦截的方法调用包括:app
使用插件是很是简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名便可。this
// ExamplePlugin.java @Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class}, @Signature( type = Executor.class, //必须为上面所支持的类 method = "query", //类中支持的方法,可从源码中查看支持哪些方法 args = {MappedStatement.class, Object.class , RowBounds.class, ResultHandler.class})}) //对应的参数Class,也可从源码中查看 public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { Object[] queryArgs = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) queryArgs[0]; Object parameter = queryArgs[1]; BoundSql boundSql = mappedStatement.getBoundSql(parameter); String sql = boundSql.getSql();//获取到SQL ,能够进行调整 String name = invocation.getMethod().getName(); queryArgs[1] = 2; //能够修改参数内容 System.err.println("拦截的方法名是:" + name); return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { } }
在配置文件中注册插件spa
<!-- mybatis-config.xml --> <plugins> <plugin interceptor="org.mybatis.example.ExamplePlugin"> <property name="someProperty" value="100"/> </plugin> </plugins>
当咱们调用query方法时,匹配拦截器的方法, 因此会执行拦截器下intercept方法,作本身的处理。插件
http://www.mybatis.org/mybatis-3/zh/configuration.html#pluginscode