mybatis+mybatisplus源码学习(五)InterceptorChain

本文详细介绍了Mybatis的拦截器InterceptorChain的实现原理,包括InterceptorChain如何添加和使用拦截器,以及Plugin的内部机制。通过Plugin类的代理方法和Signature注解,展示了如何自定义Interceptor来拦截特定方法。最后,给出一个TestInterceptor的例子,展示了如何拦截StatementHandler的prepare方法。总结中提到,拦截器的执行顺序与添加到链中的顺序相反。


前言

Mybatis通过InterceptorChain进行了很好的扩展。


一、InterceptorChain


public class InterceptorChain {
   
   
  //拦截器
  private final List<Interceptor> interceptors = new ArrayList<>();
  //动态代理拦截器
  public Object pluginAll(Object target) {
   
   
    for (Interceptor interceptor : interceptors) {
   
   
      target = interceptor.plugin(target);
    }
    return target;
  }
  //添加拦截器
  public void addInterceptor(Interceptor interceptor) {
   
   
    interceptors.add(interceptor);
  }

  public List<Interceptor> getInterceptors() {
   
   
    return Collections.unmodifiableList(interceptors);
  }

}

(1)、添加拦截器

在创建SqlSessionFactory的过程中,将插件存入InterceptorChain中

protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
   
   
...
	   if (!isEmpty(this.plugins)) {
   
   
            Stream.of(this.plugins).forEach(plugin -> {
   
   
                targetConfiguration.addInterceptor(plugin);
                LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
            });
        }
}
...
public void addInterceptor(Interceptor interceptor) {
   
   
    interceptorChain.addInterceptor(interceptor);
  }

(2)、使用拦截器

在mybatis的Configuration类中,对ParameterHandler 、ResultSetHandler 、StatementHandler 、Executor 进行增强,调用 interceptorChain.pluginAll( )方法。

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
   
   
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_lrs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值