2016-01-10 36 views
3

我想知道如果有可能替換此代碼: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呢?我的意思是定義一個在交易管理器上做同樣事情的方面。

我能夠定義一個方面和切入點,但我不明白我如何能夠在事務管理器上獲取和操作。

在此先感謝您的答案。

+0

註冊一個'TransactionInterceptor',創建一個'NameMatchMethodPointcut'來匹配你現在擁有的表達式。在TransactionInterceptor上爲你想要的方法添加不同的規則(替換'tx:advice')。 –

+0

你使用的是什麼版本的彈簧? – leeor

+0

我使用Spring 4.2.4。 –

回答

1

<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,這樣更容易設置。