我希望Spring在使用@Transactional
注释的方法上回滚事务,以防万一该方法抛出一个检查异常。这方面的一个等价的:Spring:在Java配置中定义自定义@Transactional行为
@Transactional(rollbackFor=MyCheckedException.class)
public void method() throws MyCheckedException {
}
但我需要这种行为是默认为所有@Transactional
注释,而不需要它无处不在写。我们使用Java来配置Spring(配置类)。
我尝试了spring documentation建议的配置,它只能在XML中使用。于是,我就创建这个XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" rollback-for="com.example.MyCheckedException" />
</tx:attributes>
</tx:advice>
</beans>
...并通过@ImportResource
导入。 Spring确实认识并解析了这个文件(起初我有一些错误),但它不起作用。 @Transactional
的行为没有改变。
我也尝试定义我自己的事务属性源,如this answer中所建议的。但它也使用XML配置,所以我不得不把它转换成Java这样的:
@Bean
public AnnotationTransactionAttributeSource getTransactionAttributeSource() {
return new RollbackForAllAnnotationTransactionAttributeSource();
}
@Bean
public TransactionInterceptor getTransactionInterceptor(TransactionAttributeSource transactionAttributeSource) {
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
transactionInterceptor.setTransactionAttributeSource(transactionAttributeSource);
return transactionInterceptor;
}
@Bean
public BeanFactoryTransactionAttributeSourceAdvisor getBeanFactoryTransactionAttributeSourceAdvisor(TransactionAttributeSource transactionAttributeSource) {
BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
advisor.setTransactionAttributeSource(transactionAttributeSource);
return advisor;
}
这也没有工作 - 用自己的事务属性源(不同的实例比是在创建一个弹簧保持配置)。
在Java中实现这一点的正确方法是什么?
那么,如果你只配置的东西一半那显然是行不通的。您还必须禁用'@ EnableTransactionManagement'并添加注释所做的一切... –