Spring事务失败场景(一) ——AOP切面顺序导致事务不能正确回滚

AOP切面顺序导致事务不能正确回滚

原因:事务切面的优先级最低,自定义的切面默认跟事务优先级相同,并且自定义切面在内层,若这是自定义切面没有正确抛出异常,则导致外层事务不能正常回滚

@Transactional(rollbackFor = Exception.class)
public void transfer(int from, int to, int amount) throws FileNotFoundException {
    int cash = accountMapper.findBalance(from);
    if(cash - amount >= 0) {
        accountMapper.update(form, -1* aomunt);
        new FileInputStream("aaa");
        account.update(to, amount);
    }
}

@Component
@Aspect
class MyAspect {
    @Around("execution(* transfer(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取连接点所在的对象,前置通知
        LoggerUitls.get().debug("log:{}", jointPoint.getTarget());
        
        try {
            return joinPoint.proceed();		//切入点方法执行
        }catch(Throable e) {
            e.printStackTrace();  //异常通知
            return null; 
        }finally {
            System.out.println("最终通知");
        }
    }
}

事务的执行:

  • Transaction切面
  • MyAspect切面
  • 业务代码
  • MyAspect切面: 异常没有抛出,导致事务没有执行
  • Transaction切面

解决方案:

  • 自定义切面内正确抛出异常:即事务正确回滚
    • throw new RuntimeException();
    • TranscationInterceptor.currentTransactionStatus().setRollbackOnly();
  • 让自定义切面进程先执行,即事务切面运行在自定义切面内
@Component
@Aspect
@Order(Ordered.LOWEST_PRECEDENCE -1)  //越小,优先级越高
class MyAspect {
    @Around("execution(* transfer(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        LoggerUitls.get().debug("log:{}", jointPoint.getTarget());
     
        try {
            return joinPoint.proceed();		
        }catch(Throable e) {
            throw new RuntimeException();
            //或 TranscationInterceptor.currentTransactionStatus().setRollbackOnly();
            return null; 
        }finally {
            System.out.println("最终通知");
        }
    }
}
posted @ 2022-04-11 17:10  言思宁  阅读(1255)  评论(0编辑  收藏  举报