mybatis中拦截器执行顺序

mybatis中拦截器执行顺序

拦截器初始化

org.apache.ibatis.builder.xml.XMLConfigBuilder中:

private void pluginElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      String interceptor = child.getStringAttribute("interceptor");
      Properties properties = child.getChildrenAsProperties();
      Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
      interceptorInstance.setProperties(properties);
      configuration.addInterceptor(interceptorInstance);
    }
  }
}

可以发现XMLConfigBuilderinterceptor结点下依次按顺序的添加到configuration

org.apache.ibatis.session.Configuration中:

public void addInterceptor(Interceptor interceptor) {
  interceptorChain.addInterceptor(interceptor);
}

可以看到从xml解析出来的interceptor最终被加入到interceptorChain

再看看interceptorChain是如何执行interceptor的,在org.apache.ibatis.plugin.InterceptorChain中:

public Object pluginAll(Object target) {
  for (Interceptor interceptor : interceptors) {
    target = interceptor.plugin(target);
  }
  return target;
}

按照加入的顺序依次执行interceptor操作

都知道拦截器链原理是:

interceptor1-preprocess...
interceptor2-preprocess...
interceptor3-preprocess...
target invoked...
interceptor3-postprocess...
interceptor2-postprocess...
interceptor1-postprocess...

拦截顺序

拦截顺序分成两种:对于同一对象的拦截和不同对象的拦截

不同对象的拦截

不同对象的拦截的顺序:

  • Executor
  • ParameterHandler
  • StatementHandler
  • ResultHandler
同一对象的拦截

主要看在xml中的位置,如果拦截的都是Executor:

<property name="plugins">
        <array>
            <bean "interceptor1"/>
            <bean "interceptor2"/>
        </array>
</property>

即,interceptor1interceptor2之前,那么就会先执行interceptor1,后执行interceptor2,interceptor2执行结果返回至interceptor1后作后置处理

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值