2014-10-11 92 views
1

所以我的問題圍繞着使用基於XML的模式的Spring AOP與使用AspectJ進行比較。從網上查看我一直在試圖找出爲AOP採取哪種方法。有一個特別的場景讓我略感困惑。Spring AOP:Xml vs AspectJ方法

假設我有許多具有n個方法的類,並且我想將我的方面類的建議應用於某些方法/連接點但不是全部,我可以看到在使用AspectJ時這很簡單 - 我只是將我的方面註釋應用於應該使用通知的方法。但是,從我所見過的基於xml的方法中,我將不得不爲每個方法創建一個切入點(假設它們不能被一個表達式覆蓋,即每個方法都有一個明確的名稱)和(如果我是使用基於代理的方法)每個目標/類的代理類。在這個意義上,AspectJ方法似乎更加整潔。

那麼,我對這兩種方法的理解是否正確,或者我錯過了Spring AOP的某些部分,可以爲xml方法實現更好的解決方案?

對不起囉嗦的解釋,但我想使這個場景儘可能明確...

回答

2

這聽起來像你正在嘗試Spring AOP和AspectJ之間做出選擇,但你假設Spring AOP需要基於XML的配置。它沒有。您可以使用AspectJ的註解兩個Spring AOP和AspectJ:

package com.example.app; 

import org.aspectj.lang.annotation.AfterReturning; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut; 
import org.springframework.beans.factory.annotation.Autowired; 

@Aspect 
public class NotificationAspect { 
    @Autowired private NotificationGateway notificationGateway; 

    @Pointcut("execution(* com.example.app.ItemDeleter.delete(com.example.app.Item))") 
    private void deleteItemOps() { } 

    @AfterReturning(pointcut = "deleteItemOps() && args(item)") 
    public void notifyDelete(Item item) { 
     notificationGateway.notify(item, ConfigManagementEvent.OP_DELETE); 
    } 
} 

所以,如果你想比較Spring AOP和AspectJ,它更明智的AspectJ的比較基於註解的Spring AOP的。 Spring AOP通常比較簡單(你不需要AspectJ編譯器)。因此參考文檔推薦使用Spring AOP而不是AspectJ,除非您需要更多異國情調的切入點。

UPDATE:應對下面的OP的評論,我們可以使用XML配置奉勸具體方法:

<aop:config> 
    <aop:pointcut 
     id="deleteItemOps" 
     expression="execution(* com.example.app.ItemDeleter.delete(com.example.app.Item))" /> 
    <aop:advisor 
     advice-ref="notificationAdvice" 
     pointcut-ref="deleteItemOps() && args(item)" /> 
</aop:config> 

如果你要嵌入的切入點就在<aop:advisor>,你也可以這樣做:

<aop:config> 
    <aop:advisor 
     advice-ref="notificationAdvice" 
     pointcut="execution(* com.example.app.ItemDeleter.delete(com.example.app.Item)) && args(item)" /> 
</aop:config> 

(我沒有檢查XML配置的&& args(item)一部分,但我想這是因爲我給的例子確定。如果它不工作,嘗試將其移除並隨時編輯日)

+0

是的我想我是問使用spring aop與xml配置相比,使用spring aop與aspectj註解,使用它與aspectj註解似乎允許我們將我們的方面應用到單獨的方法/連接點而使用xml配置意味着我們將它應用到切入點表達式中包含的一個類或一組方法中 - spring與aspectj似乎在這方面提供了更多的靈活性? – Shane 2014-10-12 00:53:30

+0

是的,我認爲這可能是你的意圖。考慮更新標題以反映這一點。無論如何,我更新了回覆。 – 2014-10-12 01:06:06

+0

謝謝,會做,我懷疑上述解決方案將需要一個不同的顧問標籤爲每個切入點/方法的建議將被應用? – Shane 2014-10-12 01:20:37