Springboot整合Aop配置全局事务@林

一般小的项目比较适合直接在ServiceImpl-逻辑处理层的实现方法上直接添加@Transactional注解,但是大一点的项目要是每个方法都去添加这个注解就显得比较鸡肋,因此可以通过Aop实现全局事务处理,我们只需要在Service层添加一个切面,通过方法名控制事务的属性,我们的项目可以两个都用,也可以只用一个就行,接下来看看具体操作。

1.添加依赖

在pom.xml中添加Aop的架包依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.开启事务注解

@EnableTransactionManagement
在启动类添加事务启动注解

@Log4j2
@EnableCaching //启动缓存注解
@EntityScan(value={"com.gd.base"})
@ComponentScan(value = {"com.gd.**"},basePackages = {"com.gd.**"})
@EnableJpaRepositories(basePackages = "com.gd.base")
@SpringBootApplication
//开启事务注解功能---只需要在自己的额项目中添加这一个注解就行
@EnableTransactionManagement
public class GdServiceApplication {

    public static void main(String[] args) {
        //SpringApplication.run(GdServiceApplication.class, args);
        ConfigurableApplicationContext application = SpringApplication.run(GdServiceApplication.class, args);
        Environment env = application.getEnvironment();
        //swagger接口文档地址打印
        logApplicationStartup(env);
    }

3.注解事务使用–注解事务

在ServiceImpl的方法上面添加注解

@Service
public class SysStaticServiceImpl implements SysStaticService {
    /**
     * @Description TODO 添加静态值类型
     * @param token
     * @param sysStaticTypeDto
     * @return
     */
    @Transactional//事务注解,具体添加什么事务可以去添加注解属性,这里就不具体介绍
    public CommonResult addSysStaticType(String token, SysStaticTypeDto sysStaticTypeDto){
        //业务逻辑处理
        return new CommonResult(ResultCodeEnums.SUCCESS.getCode(), ResultCodeEnums.SUCCESS.getMessage());
    }
}

实现全局事务

创建一个切面类,具体实现可以看看代码以及注释

/**
 * @Auther: tangxl
 * @Date:2021年12月21日20:51:27
 * @Description: TODO 全局事务配置
 */
@Configuration
@Aspect
public class TransactionManagerConfig {
    private final static Logger logger = LoggerFactory.getLogger(TransactionManagerConfig.class);
    /**
     * 配置方法过期时间,默认-1,永不超时,单位毫秒
     */
    private static final int AOP_TIME_OUT = 50000;
    /**
     * 配置切入点表达式 : 指定哪些包中的类使用事务
     */
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.gd.gd_service.service.impl.*.*(..)))";
    //事务管理器
    @Autowired
    private TransactionManager transactionManager;
    /**
     * 声明业务方法的事务属性
     */
    @Bean
    public TransactionInterceptor txAdvice(){
        /**
         * 这里配置只读事务
         * 查询方法, 只读事务,不做更新操作
         */
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        /**
         * 增、删、改 需要的事务
         * 必须带事务
         * 当前存在事务就使用当前事务,当前不存在事务,就开启一个新的事务
         */
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
        // 设置回滚规则:什么异常都需要回滚
        requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        // 当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务
        requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiredTx.setTimeout(AOP_TIME_OUT);
        /**
         * 无事务地执行,挂起任何存在的事务
         */
        RuleBasedTransactionAttribute noTx = new RuleBasedTransactionAttribute();
        noTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);

        /**
         * 设置方法对应的事务
         */
        Map<String, TransactionAttribute> methodMap = new HashMap<>();
        // 可以提及事务或回滚事务的方法
        //只读事务
        methodMap.put("get*", readOnlyTx);
        methodMap.put("query*", readOnlyTx);
        methodMap.put("find*", readOnlyTx);
        methodMap.put("list*", readOnlyTx);
        methodMap.put("count*", readOnlyTx);
        methodMap.put("exist*", readOnlyTx);
        methodMap.put("search*", readOnlyTx);
        methodMap.put("fetch*", readOnlyTx);
        //写事务
        methodMap.put("add*", requiredTx);
        methodMap.put("save*", requiredTx);
        methodMap.put("insert*", requiredTx);
        methodMap.put("update*", requiredTx);
        methodMap.put("modify*", requiredTx);
        methodMap.put("delete*", requiredTx);
        methodMap.put("creat*", requiredTx);
        methodMap.put("edit*", requiredTx);
        methodMap.put("remove*", requiredTx);
        methodMap.put("repair*", requiredTx);
        methodMap.put("binding*", requiredTx);
        //无事务
        methodMap.put("noTx*", noTx);
        // 其他方法无事务,只读
        methodMap.put("*", readOnlyTx);

        //声明一个通过方法名字配置事务属性的对象
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.setNameMap(methodMap);

        //返回事务拦截器
        TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
        return txAdvice;
    }

    @Bean(name = "txAdviceAdvisor")
    public Advisor txAdviceAdvisor(TransactionInterceptor txAdvice) {
        logger.info("===============================创建txAdviceAdvisor===================================");
        //配置事务切入点表达式
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        //增强事务,关联切入点和事务属性
        return new DefaultPointcutAdvisor(pointcut, txAdvice);
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hippoDocker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值