繁体   English   中英

Spring:在Java配置中定义自定义@Transactional行为

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM