[英]Spring: define custom @Transactional behavior in Java config
我希望Spring在使用@Transactional
注釋的方法上回滾事務,以防該方法引發已檢查的異常。 等效項:
@Transactional(rollbackFor=MyCheckedException.class)
public void method() throws MyCheckedException {
}
但是我需要所有@Transactional
注釋都將此行為設置為默認行為,而無需到處編寫它。 我們正在使用Java來配置Spring(配置類)。
我嘗試了spring文檔建議的配置,該配置僅在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
的行為未更改。
我也嘗試按照此答案中的建議定義自己的交易屬性源。 但是它也使用了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;
}
這也不起作用-Spring繼續使用其自己的事務屬性源(與配置中創建的實例不同的實例)。
用Java實現此目的的正確方法是什么?
您應該實施自己的注釋- 參考
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor=MyCheckedException.class)
public @interface TransactionalWithRollback {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.