MyBatis-自定义Interceptor实战

1、编写自己的插件类

1)实现 Interceptor 接口

           这个是所有的插件必须实现的接口。

2)添加@Intercepts({@Signature()}),指定拦截的对象和方法、方法参数

         方法名称+参数类型,构成了方法的签名,决定了能够拦截到哪个方法。
问题:拦截签名跟参数的顺序有关系吗?

3)实现接口的 3 个方法

 // 用于覆盖被拦截对象的原有方法(在调用代理对象 Plugin 的 invoke()方法时被调用)
Object intercept(Invocation invocation) throws Throwable;
// target 是被拦截对象,这个方法的作用是给被拦截对象生成一个代理对象,并返回它
Object plugin(Object target);
// 设置参数
void setProperties(Properties properties);

2、插件注册,在 mybatis-config.xml 中注册插件

<plugins> 
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <property name="offsetAsPageNum" value="true"/> 
        ……后面全部省略…… 
    </plugin>
</plugins>

3、插件登记

         MyBatis 启 动 时 扫 描 <plugins> 标 签 , 注 册 到 Configuration 对 象 的
InterceptorChain 中。property 里面的参数,会调用 setProperties()方法处理。
以上就是编写和使用自定义插件的全部步骤。

4. 案例

自定义拦截器

@Intercepts({ @Signature(type = StatementHandler.class, method = "query", args = { Statement.class, ResultHandler.class}) })
@Slf4j
public class SQLInterceptor implements Interceptor {
    private Properties properties;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        log.info("{}获取到SQL语句:{}",properties.getProperty("serverName"),sql);

        try {
            return invocation.proceed();
        }finally {
            long endTime = System.currentTimeMillis();
            log.info("SQL执行耗时:{} ms", (endTime-startTime));
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties=properties;
    }
}

添加到配置中

<plugins>
        <plugin interceptor="com.gupaoedu.interceptor.MyPageInterceptor">
        </plugin>
      
 </plugins>-->

或者通过配置类

        Properties sqlProperties = new Properties();        
        sqlProperties.setProperty("serverName","testServer");
        sqlInterceptor.setProperties(sqlProperties);
        sessionFactory.setPlugins(new Interceptor[] {interceptor,sqlInterceptor});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值