springboot 配置事务
程序员文章站
2024-03-09 10:04:35
...
开启事务注解
pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@EnableTransactionManagement
@EnableAspectJAutoProxy (exposeProxy = true) // aop 切面
配置事务代码
@Aspect
@Configuration
public class TransactionAdviceConfig {
private Logger logger = LoggerFactory.getLogger(TransactionAdviceConfig.class);
private static final String POINTCUT_EXPRESSION = "execution(* com..service.impl..*ServiceImpl.*(..))";
@Autowired
private PlatformTransactionManager transactionManager;
@Bean
public TransactionInterceptor txAdvice() {
RuleBasedTransactionAttribute txRequired = new RuleBasedTransactionAttribute();
txRequired.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
txRequired.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
RuleBasedTransactionAttribute txRequiredReadOnly = new RuleBasedTransactionAttribute();
txRequiredReadOnly.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
txRequiredReadOnly.setReadOnly(true);
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
source.addTransactionalMethod("do*", txRequired);
source.addTransactionalMethod("get*", txRequiredReadOnly);
source.addTransactionalMethod("select*", txRequiredReadOnly);
source.addTransactionalMethod("count*", txRequiredReadOnly);
return new TransactionInterceptor(transactionManager, source);
}
@Bean
public Advisor txAdviceAdvisor() {
logger.info("===============================创建txAdviceAdvisor===================================");
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
}
上一篇: 2020年9月工作问题记录
下一篇: go递归打印指定目录下的所有文件及文件夹