spring AOP 事务 与 Afterthrowing 冲突的解决办法

  

今天在开发过程中发现一个很奇怪的问题,在模拟事务回滚过程中,发现事务回滚没问题,异常也输出了,但之前配置的afterthrowing记录出错日志配置却始终不好用,根本不会执行到afterthrowing配置的方法内但afterreturning配置 却没有问题,去掉配置的AOP事务后,afterthrowing一切正常。。。仔细想想整个程序执行步骤,考虑到事务的回滚用到的是环绕通知around,是不是两个同时执行,log拦截器包含在了事务拦截器里,所以当事务遇到了错误回滚也直接将插入异常日志一同回滚了?能不能在事务执行遇到exception回滚以后再去控制它去进入afterthowing配置的方法?于是我又仔细看了看spring 关于aop的配置,惊喜的发现一个"order"参数,这个参数是用来控制aop通知的优先级,值越小,优先级越高,于是我手动设置了事务与异常日志两个aop通知的order 参数,控制log拦截器在事务的around之外,不出我所料,问题最终得到解决~~

以下是部分代码,可供参考:

<!-- AOP 事务 -->

   <aop:config>
        <aop:pointcut id="serviceMethods"
            expression="execution(* hamob.*.*(..))" />
        <aop:advisor advice-ref="txAdvice"
            pointcut-ref="serviceMethods" order="2"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
         <tx:method name="add*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
         <tx:method name="update*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
         <tx:method name="delete*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

<!-- AOP 日志管理 -->
    <aop:config>
        <aop:aspect ref="logadvice" order="3">
            <aop:pointcut id="logInsertMethods" expression="execution(* hamob.*.save*(..))"/>
            <aop:after-returning method="saveLog" pointcut-ref="logInsertMethods" returning="rvt"/>
        </aop:aspect>
    </aop:config>
    <!-- AOP throwing管理 -->
    <aop:config>
        <aop:aspect ref="logadvice" order="1">
            <aop:pointcut id="throwinglog" expression="execution(* hamob.*.save*(..))"/>
            <aop:after-throwing pointcut-ref="throwinglog" throwing="throwable" method="afterThrowing"/>
        </aop:aspect>
    </aop:config>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值