原创

spring boot 自定义事务注解

前言

在开发中,需要在controller中添加事务,但@Transactional只能添加在service中,加在controller中无效

原因

springboot项目启动时,会在spring容器中,查找使用@Transactional的Bean,但是controller在spring mvc容器中。spring容器中,找不到spring mvc容器的Bean,因此在controller中,无法使用@Transactional

解决方案

新建自定义事务注解,在controller中使用自定义事务注解

新建 @ControllerTransaction

package com.lsb.aspect.annotation;

import java.lang.annotation.*;

/**
 * @author liushengbing
 * @ClassName ControllerTransaction
 * @Description Controller 事务
 * @createTime 2022/11/11 18:29
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerTransaction {
}

新建 ControllerTransactionAspect

package com.lsb.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @author liushengbing
 * @ClassName ControllerTransactionAspect
 * @Description Controller 事务 aop
 * @createTime 2022/11/11 18:32
 */
@Aspect
@Component
public class ControllerTransactionAspect {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Pointcut("@annotation(com.moshu.aspect.annotation.ControllerTransaction)")
    public void controllerTransactionPointcut(){

    }

    @Around("controllerTransactionPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 开启事务
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);
        try{
            // 执行方法
            Object result = point.proceed();
            // 执行成功 提交事务
            transactionManager.commit(status);
            // 返回执行结果
            return result;
        }catch (Throwable throwable){
            // 执行方法出错,回滚事务
            transactionManager.rollback(status);
            // 重新抛出这个错误
            throw throwable;
        }
    }

}
正文到此结束