problems_spring
目录
- problems_spring
- 1 记录一个spring事务未生效的问题
- 2
- 3
- 4
- 5
- 6
problems_spring
1 记录一个spring事务未生效的问题
DESC:
public class AServiceImpl implements AService {
@Autowired
private BService bService;
methodA() {
methodB();
bService.methodC();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
methodB() {
...
}
}
methodA()方法中先调用methodB(),再调用methodC()。其中,methodB()和methodA()属于同一个对象,methodC()属于另一个对象。并且,methodC()的执行,必须要依赖methodB()的增删改的执行结果。可是实际发现methodB()的增删改的执行结果并没有立刻持久化到数据库,而是在methodA()彻底执行完后才持久化到数据库,也就是说,methodB()仍然和methodA()在同一个事务中,这导致methodC()的执行结果错误。
RCA:
spring事务,方法上添加的注解 @Transactional(propagation = Propagation.REQUIRES_NEW) 不生效。具体原因参考下面的参考链接。
SOLUTION:
方法1:将methodB()移到另一个对象中;
方法2:将methodB()中的调用的实际进行增删改的方法上,添加注解 @Transactional(propagation = Propagation.REQUIRES_NEW),methodB()本身去掉该注解 @Transactional;
方法3:从beanFactory中获取bean SpringContextUtil.getBean(…)
reference: https://blog.csdn.net/hepei120/article/details/78058468
https://www.jianshu.com/p/e57e55e98814