8、插件(plugins)拦截器的配置详解

来源:互联网 发布:公务员网络培训系统 编辑:程序博客网 时间:2024/06/15 16:30

Mybatis拦截器的介绍

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
它可以拦截Executor 、ParameterHandler 、ResultSetHandler 、StatementHandler 的部分方法,处理我们自己的逻辑。

自定义拦截器

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

    <plugins>        <plugin interceptor="com.lf.plugin.MyBatisPlugin">            <property name="name" value="你好"></property>        </plugin>    </plugins>
package com.lf.plugin;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.plugin.*;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import java.util.Properties;/** * Created by LF on 2017/6/11. */@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})})public class MyBatisPlugin implements Interceptor {    @Override    //只有Intercepts在定义的方法才会被拦截    public Object intercept(Invocation invocation) throws Throwable {        String name = invocation.getMethod().getName();        System.err.println("拦截的方法名是:" + name);        return invocation.proceed();    }    @Override    public Object plugin(Object target) {        return Plugin.wrap(target, this);    }    @Override    public void setProperties(Properties properties) {        Object name = properties.getProperty("name");//你好        System.err.println(name);    }}

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

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

原创粉丝点击