前言
spring事务失效场景可能大家在很多文章都看过了,所以今天就水一篇,看大家能不能收获一些不一样的东西。直接进入主题
spring事务失效场景以及原因
场景一:抛出受检异常
@Service
public class TranInvalidCaseByThrowCheckException {
@Autowired
private UserService userService;
@Transactional
public boolean add(User user) throws FileNotFoundException {
boolean isSuccess = userService.save(user);
new FileInputStream("1.txt");
return isSuccess;
}
}
@Test
public void testThrowCheckException() throws Exception{
boolean randomBoolean = new Random().nextBoolean();
boolean isSuccess = false;
TranInvalidCaseByThrowCheckException tranInvalidCaseByThrowCheckException = applicationContext.getBean(TranInvalidCaseByThrowCheckException.class);
if(randomBoolean){
System.out.println("配置@Transactional(rollbackFor = Exception.class)");
isSuccess = tranInvalidCaseByThrowCheckException.save(user);
}else{
System.out.println("配置@Transactional");
tranInvalidCaseByThrowCheckException.add(user);
}
Assert.assertTrue(isSuccess);
}
失效原因: spring默认只会回滚非检查异常和error异常
解决方案:
配置rollbackFor
场景二:service没有托管给spring
public class TranInvalidCaseWithoutInjectSpring {
private UserService userService;
public TranInvalidCaseWithoutInjectSpring(UserService userService) {
this.userService = userService;
}
@Transactional
public boolean add(User user){
boolean isSuccess = userService.save(user);
int i = 1 % 0;
return isSuccess;
}
}
@Test
public void testServiceWithoutInjectSpring(){
boolean randomBoolean = new Random().nextBoolean();
TranInvalidCaseWithoutInjectSpring tranInvalidCaseWithoutInjectSpring;
if(randomBoolean){
tranInvalidCaseWithoutInjectSpring = applicationContext.getBean(TranInvalidCaseWithoutInjectSpring.class);
System.out.println("service已经被spring托管");
}else{
tranInvalidCaseWithoutInjectSpring = new TranInvalidCaseWithoutInjectSpring(userService);
System.out.println("service没被spring托管");
}
boolean isSuccess = tranInvalidCaseWithoutInjectSpring.add(user);
Assert.assertTrue(isSuccess);