Spring采用xml方式配置AOP 改变通知顺序结果改变

这篇博客是为了求解,为什么xml中配置通知顺序会影响结果,通知类型xml文档中明确标注了出来,为什么会出现最终通知比后置通知、异常通知提前执行的情况?希望有知道原因的大神可以解答!
目前尚未清楚原因

正常代码顺序:

<!-- 配置AOP -->
<aop:config>
    <!-- 配置通用切入点 -->
    <aop:pointcut id="pt1" expression="execution(* com.vector.service.impl.*.*(..))"/>

    <!-- 配置切面 -->
    <aop:aspect id="txAdvice" ref="tManager">
        <!-- 配置前置通知,开启事务 -->
        <aop:before method="beginTransaction" pointcut-ref="pt1"/>
        <!-- 配置后置通知,提交事务 -->
        <aop:after-returning method="commitTransaction" pointcut-ref="pt1"/>
        <!-- 配置异常通知,回滚事务 -->
        <aop:after-throwing method="rollbackTransaction" pointcut-ref="pt1"/>
        <!-- 配置最终通知,释放连接 -->
        <aop:after method="release" pointcut-ref="pt1"/>
    </aop:aspect>
</aop:config>

执行结果(无异常)

开始事务
提交
关闭连接

执行结果(有异常)

开始事务
回滚
关闭连接

调整后代码顺序:

  • 将最终通知放在后置通知之前
<!-- 配置AOP -->
<aop:config>
    <!-- 配置通用切入点 -->
    <aop:pointcut id="pt1" expression="execution(* com.vector.service.impl.*.*(..))"/>

    <!-- 配置切面 -->
    <aop:aspect id="txAdvice" ref="tManager">
        <!-- 配置前置通知,开启事务 -->
        <aop:before method="beginTransaction" pointcut-ref="pt1"/>
        <!-- 配置最终通知,释放连接 -->
        <aop:after method="release" pointcut-ref="pt1"/>
        <!-- 配置后置通知,提交事务 -->
        <aop:after-returning method="commitTransaction" pointcut-ref="pt1"/>
        <!-- 配置异常通知,回滚事务 -->
        <aop:after-throwing method="rollbackTransaction" pointcut-ref="pt1"/>
    </aop:aspect>
</aop:config>

执行结果(无异常)

开始事务
关连接
执行回滚事务,但连接还回线程池,没有连接可以提交事务

执行结果(有异常)

开始事务
关连接
执行提交事务,但连接还回线程池,没有连接可以提交事务

调整后代码顺序:

  • 前置-最终-异常-后置
<!-- 配置AOP -->
    <aop:config>
        <!-- 配置通用切入点 -->
        <aop:pointcut id="pt1" expression="execution(* com.vector.service.impl.*.*(..))"/>

        <!-- 配置切面 -->
        <aop:aspect id="txAdvice" ref="tManager">
            <!-- 配置前置通知,开启事务 -->
            <aop:before method="beginTransaction" pointcut-ref="pt1"/>
            <!-- 配置最终通知,释放连接 -->
            <aop:after method="releaseTransaction" pointcut-ref="pt1"/>
            <!-- 配置异常通知,回滚事务 -->
            <aop:after-throwing method="rollbackTransaction" pointcut-ref="pt1"/>
            <!-- 配置后置通知,提交事务 -->
            <aop:after-returning method="commitTransaction" pointcut-ref="pt1"/>
        </aop:aspect>
    </aop:config>

执行结果(无异常)

开始事务
关连接
执行回滚事务,但连接还回线程池,没有连接可以提交事务

执行结果(有异常)

开始事务
关连接
执行提交事务,但连接还回线程池,没有连接可以提交事务

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值