spring事务-Exception不会回滚

在Spring中,事务管理默认情况下只会在遇到运行时异常(RuntimeException)和错误(Error)时进行回滚。对于检查型异常(Checked Exception),Spring事务默认不会进行回滚。

如果你想让Spring事务在遇到检查型异常时也进行回滚,你可以采取以下几种方法:

方法一:使用@Transactional注解的rollbackFor属性

你可以在@Transactional注解中指定哪些异常发生时应该触发事务回滚,包括检查型异常。

java 复制代码
import org.springframework.transaction.annotation.Transactional;


@Service
public class MyService {


    @Transactional(rollbackFor = Exception.class)
    public void myMethod() throws Exception {
        // ... 业务逻辑 ...
        throw new Exception("发生了一个检查型异常");
    }
}

在上面的例子中,rollbackFor = Exception.class表示任何类型的异常(包括运行时异常和检查型异常)都会触发事务回滚。

方法二:全局配置

如果你想对整个应用进行全局配置,让所有的检查型异常都触发事务回滚,你可以在Spring配置文件中进行如下设置:

xml 复制代码
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" rollback-for="java.lang.Exception"/>
    </tx:attributes>
</tx:advice>


<aop:config>
    <aop:pointcut id="serviceOperation" expression="execution(* com.yourpackage..*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
</aop:config>

或者在Java配置类中使用@EnableTransactionManagementTransactionInterceptor

java 复制代码
@Configuration
@EnableTransactionManagement
public class TransactionConfig implements TransactionManagementConfigurer {


    @Autowired
    private PlatformTransactionManager transactionManager;


    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return transactionManager;
    }


    @Bean
    public TransactionInterceptor txInterceptor() {
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        RuleBasedTransactionAttribute transactionAttribute = new RuleBasedTransactionAttribute();
        transactionAttribute.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        source.addTransactionalMethod("*", transactionAttribute);
        return new TransactionInterceptor(transactionManager, source);
    }
}

Java

方法三:编程式事务管理

如果你使用编程式事务管理,可以在调用TransactionStatussetRollbackOnly方法来标记事务需要回滚。

java 复制代码
@Service
public class MyService {


    @Autowired
    private PlatformTransactionManager transactionManager;


    public void myMethod() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            // ... 业务逻辑 ...
            throw new Exception("发生了一个检查型异常");
        } catch (Exception ex) {
            status.setRollbackOnly();
        } finally {
            transactionManager.commit(status);
        }
    }
}

注意事项

  • 使用rollbackFor属性时要小心,确保不会因为过于宽泛的异常捕获导致意外的数据不一致。
  • 在设计服务层时,应该尽量避免抛出检查型异常,而是使用运行时异常来表示错误情况,这样可以更好地利用Spring的事务管理机制。

通过上述方法,你可以控制Spring事务在不同异常情况下的行为,确保数据的完整性和一致性。

相关推荐
张3蜂1 天前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
Coder_Boy_1 天前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
7哥♡ۣۖᝰꫛꫀꪝۣℋ1 天前
Spring-cloud\Eureka
java·spring·微服务·eureka
一灰灰blog1 天前
Spring AI中的多轮对话艺术:让大模型主动提问获取明确需求
数据库·人工智能·spring
Java水解1 天前
【JAVA 进阶】Spring AOP核心原理:JDK与CGLib动态代理实战解析
后端·spring
暮色妖娆丶1 天前
Spring 源码分析 BeanFactoryPostProcessor
spring boot·spring·源码
暮色妖娆丶1 天前
SpringBoot 启动流程源码分析 ~ 它其实不复杂
spring boot·后端·spring
Coder_Boy_1 天前
Deeplearning4j+ Spring Boot 电商用户复购预测案例中相关概念
java·人工智能·spring boot·后端·spring
雨中飘荡的记忆1 天前
Spring Batch实战
java·spring
callJJ1 天前
Spring AI 文本聊天模型完全指南:ChatModel 与 ChatClient
java·大数据·人工智能·spring·spring ai·聊天模型