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事务在不同异常情况下的行为,确保数据的完整性和一致性。

相关推荐
Java小白程序员2 小时前
Spring Framework:Java 开发的基石与 Spring 生态的起点
java·数据库·spring
甄超锋3 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
还是鼠鼠4 小时前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
还是大剑师兰特5 小时前
Spring面试题及详细答案 125道(1-15) -- 核心概念与基础1
spring·大剑师·spring面试题·spring教程
python_1368 小时前
web请求和响应
java·spring·github
ciku10 小时前
Spring AI Starter和文档解读
java·人工智能·spring
javadaydayup10 小时前
Apollo 凭什么能 “干掉” 本地配置?
spring boot·后端·spring
耳东哇13 小时前
spring ai-openai-vl模型应用qwen-vl\gpt-文字识别-java
java·人工智能·spring
long3161 天前
java 策略模式 demo
java·开发语言·后端·spring·设计模式
柏油1 天前
Spring @Cacheable 解读
redis·后端·spring