Spring AOP:将XML替换为事务管理的注释



我想知道是否可以替换此代码:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="get*" read-only="true" />  
        <tx:method name="saveFile" isolation="SERIALIZABLE" propagation="REQUIRED" no-rollback-for="BusinessException" />
        <tx:method name="*" />
    </tx:attributes>
</tx:advice>
<!--Transaction aspect-->
<aop:config>
    <aop:pointcut id="businessOperation"
        expression="execution(* com.application.app.business.*.*(..)) || execution(* com.application.app.logic..*.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="businessOperation" />
</aop:config>   

使用完整的注释而根本没有 XML?我的意思是在事务管理器上定义一个方面做同样的事情。

我能够定义一个方面和切入点,但我看不出如何获得事务管理器并采取行动。

提前感谢您的回答。

<tx:advice />所做的基本上是注册一个TransactionInterceptor,该注入PlatformTransactionManager并为<tx:method />元素设置不同的规则。

要复制这一点,应该在基于 Java 的配置中完成如下操作。

@Bean
public TransactionInterceptor transactionInterceptor(PlatformTransactionManager transactionManager) {
    return new TransactionInterceptor(transactionManager, transactionAttributeSource());
}
@Bean
public NameMatchTransactionAttributeSource transactionAttributeSource() {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    RuleBasedTransactionAttribute gets = new RuleBasedTransactionAttribute();
    gets.setReadOnly(true);
    RuleBasedTransactionAttribute saveFile = new RuleBasedTransactionAttribute(8, Collections.singletonList(new NoRolebackRuleAttribute(BusinessException.class);
    Map<String, AttributeSource> matches = new HashMap<>();
    matches.put("get*", gets);
    matches.put("saveFile", saveFile);
    return tas;
}

现在下一部分是您需要手动定义点切割。为此,您需要构建一个AspectJExpressionPointcutAdvisor.这也是<aop:pointcut />标签所做的。

@Bean
public AspectJExpressionPointcutAdvisor transactionAdvisor(TransactionInterceptor advice) {
    AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
    advisor.setAdvice(advice);
    advisor.setExpression("execution(* com.application.app.business.*.*(..)) || execution(* com.application.app.logic..*.*(..))");
    return advisor;
}

如果要复制 xml 配置,这应该是您需要执行的操作。但是,我建议改为@Transactional,这更容易设置。

最新更新