介绍
在每个方法名加一个transaction注解太麻烦
所以写了一个全局事务处理的切面类
在此作为一个记录springboot 的版本是2.1.9.RELEASE
数据库用的是mysql8.0
数据源用的是druid1.2.8
1.目录结构如下:
2.全局事务切面类代码如下:
package com.company.hncjsc.stoneV1.api.common.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.*;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 全局事务切面配置类
* @Author 小轩
* @Date 2022/4/8 14:16
* @Version 1.0
*/
@EnableTransactionManagement
@Aspect
@Configuration
public class GlobalTransactionConfig {
//写事务的超时时间为10秒
private static final int TX_METHOD_TIMEOUT = 10;
//stoneV1包下所有service包或者service的子包的任意类的任意方法
private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.company.hncjsc.stoneV1.service..*.*(..))";
@Resource
private PlatformTransactionManager 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(TX_METHOD_TIMEOUT);
/***
* 无事务地执行,挂起任何存在的事务
*/
RuleBasedTransactionAttribute noTx = new RuleBasedTransactionAttribute();
noTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
Map<String, TransactionAttribute> txMap = new HashMap<>();
//只读事务 暂留不加 2022 4.26
// txMap.put("info*", readOnlyTx);
// txMap.put("list*", readOnlyTx);
//无事务
// txMap.put("noTx*", noTx);
//写事务
txMap.put("insert*", requiredTx);
txMap.put("update*", requiredTx);
txMap.put("delete*", requiredTx);
txMap.put("deletes*", requiredTx);
txMap.put("status*", requiredTx);
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
source.setNameMap(txMap);
return new TransactionInterceptor(transactionManager, source);
}
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
}