欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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());
    }

}
相关标签: 工作问题记录