Spring custom annotations implement transactions

First of all, there are two ways of transactions in spring: programming transactions and declarative transactions

Programming Transactions :

Get the transaction manager DataSourceTransactionManager in the project

Commit rollback operations using transaction management

@Component
public class TransactionUtils {
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    //获取当前事务
    public TransactionStatus begin(){
        //采用默认传播行为
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        return transaction;
    }
    //提交
    public void commit(TransactionStatus transaction){
        dataSourceTransactionManager.commit(transaction);
    }
    public void rollback(TransactionStatus transaction){
        dataSourceTransactionManager.rollback(transaction);
    }
}

Business Layer

@RestController
public class TxServiceImpl {
    @Autowired
    private TransactionUtils transactionUtils;
    //采取事务
    @GetMapping("/tx")
    public String insertUser(User user){
        TransactionStatus begin == null;
        //begin开启事务,若不提交相当于对数据使用行锁
        try {
            begin = transactionUtils.begin();
            String res = userMapper.insert(user)>0?"成功":"失败";
            int j = 1/user.getUserId();
            transactionUtils.commit(begin);
            return res;
        }catch (Exception e){
            if (begin != null){
                transactionUtils.rollback(begin);
                return "系统错误";
            }

        }
    }
}

Strong code repetition and good scalability

Declare transaction :

Just add the annotation @Transactional

When the method is executed, aop takes the interception, and determines whether it is successful or abnormal and takes the corresponding action.

Failure problem:

When an exception is caught with try in the method, the exception will not be thrown to aop, and it will not be rolled back.

Need to roll back manually to use in catch

TransactionAspectSupport.currentTransactionStatus().set
RollbackOnly();

custom annotation

Create annotations

//作用范围
@Target({ElementType.METHOD,ElementType.TYPE})
//通过反射机制获取注解
@Retention(RetentionPolicy.RUNTIME)
@Inherited
//注释文档
@Documented
public @interface MyTransactional {
}

Define aop interception method

@Component
@Aspect
public class ExtTransactionalAop {
    @Autowired
    private TransactionUtils transactionUtils;
    //拦截方法上有自定义注解 走环绕通知
    @Around(value = "@annotation(com.lzq.aop.MyTransactional)")
    public Object around(ProceedingJoinPoint joinPoint){
        TransactionStatus begin = null;
        try {
            begin = transactionUtils.begin();
            //获取目标方法
            Object res = joinPoint.proceed();
            transactionUtils.commit(begin);
            return res;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            if (begin != null){
                transactionUtils.rollback(begin);
            }
            return "系统错误";
        }
    }
}

At this point, you can add custom annotations to the method

Guess you like

Origin blog.csdn.net/weixin_52210557/article/details/123684360