欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring 注解 事务,声明事务混用--解决问题

程序员文章站 2024-03-03 19:42:40
...

Spring 事务 混用


xml 事务和注解事务最好不要一起 坑太多了,一个aop中 存在两个 org.springframework.transaction.interceptor.TransactionInterceptor 而且各钟情况错中复杂,如果两个是 Propagation.PROPAGATION_REQUIRED,Propagation.REQUIRES_NEW 不同的顺序特别是异常产生的时候会造成不同的影响
Propagation.PROPAGATION_REQUIRED -> Propagation.REQUIRES_NEW (异常)
如果调用者为 Propagation.PROPAGATION_REQUIRED 没有开启 globalRollbackOnParticipationFailure 那么局部异常,导致全局回滚。
Propagation.REQUIRES_NEW -> Propagation.PROPAGATION_REQUIRED(异常)
如果调用者为 Propagation.PROPAGATION_REQUIRED 没有开启 globalRollbackOnParticipationFailure,由于内层事务使用了上一个事务Propagation.REQUIRES_NEW,相对于这个方法是一个新的事务,调用者捕获异常不会影响事务。
这个仅仅是两种不同隔离级别的分析,其他的场景会出现什么样的幺蛾子未知。
最好的方式是只有一个最近看同事配置的, 如果存在注解那么 xml 配置的就不生效,简单了事

<aop:config>
    <aop:pointcut id="ao_bo"
                    expression="(execution(* com.xyz.myapp.service.*.*(..)))and !(@annotation(org.springframework.transaction.annotation.Transactional) or @within(org.springframework.transaction.annotation.Transactional)))"/>
    <aop:advisor pointcut-ref="ao_bo" advice-ref="defaultTxAdvice"/>
</aop:config>


globalRollbackOnParticipationFailure 让主事务决定回滚

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
        <!--https://www.iteye.com/blog/jsczxy2-1773795-->
        <property name="globalRollbackOnParticipationFailure" value="false" />
</bean>


因此在同一个事务中,局部异常了,是否回滚有调用者决定,如果都捕获异常了可以不用回滚,这个看自己的需求是否添加这个配置。


org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only 不然会抛出这个异常。

ServiceA {
  void methodA() {
     insertDb();
     try{
         ServiceB.methodB();  
     }catch(Exception e){
         logger.error("异常",e);
     }
  }
}  

ServiceB {    
 void methodB() { 
     throw new BizException("业务异常");
 }  
}

添加一个两个xml 注解共存的拦截器图
最好的方式,有注解没有xml,只要一个即可,有他没有我
spring 注解 事务,声明事务混用--解决问题

更多

系列文章一: spring 注解 事务,声明事务共存—有bug
系列文章二:spring 注解 事务,声明事务混用–解决问题
系列文章三:spring 事务采坑-xml注解 事务混用
系列文章四: spring 事务背后的故事
更多汪小哥

相关标签: spring 原理分析