【问题标题】:Spring: define custom @Transactional behavior in Java configSpring:在 Java 配置中定义自定义 @Transactional 行为
【发布时间】:2016-11-09 04:39:45
【问题描述】:

我希望 Spring 在使用 @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;
}

这也不起作用 - Spring 继续使用自己的事务属性源(与配置中创建的实例不同的实例)。

在 Java 中实现此目的的正确方法是什么?

【问题讨论】:

  • 好吧,如果你只配置了一半的东西,那么显然它是行不通的。您还必须禁用 @EnableTransactionManagement 并添加该注释所做的一切......

标签: java spring transactions


【解决方案1】:

您应该实现自己的注释 - reference

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor=MyCheckedException.class)
public @interface TransactionalWithRollback {
}

【讨论】:

  • 是的,我也在考虑这个选项,但我不喜欢的是自定义注释必须在任何地方使用,而不是标准的 @Transactional 注释,将来某个地方的人可能会忘记这会产生错误。
猜你喜欢
  • 2018-12-24
  • 2020-02-02
  • 1970-01-01
  • 2018-12-11
  • 2013-07-23
  • 1970-01-01
  • 2020-10-02
  • 2020-11-06
  • 1970-01-01
相关资源
最近更新 更多