2011-09-27 166 views
1

我正在首次試驗Spring AOP並陷入XML配置中。我試圖獲取基於AOP的「日誌記錄」的模擬版本,並使用MethodInterceptor來包裝特定的方法調用,並在這些方法調用之前和之後執行一些簡單的System.out.println語句。簡單的東西,對吧?Spring AOP配置(XML)

所以我的項目有很多課,其中兩個是FizzBuzz。 Fizz有一個名爲foo()的方法,Buzz有一個名爲wapap()的方法。每個這些方法在運行時調用的時候,我希望我的LoggingInterceptor身邊人執行它的invoke()方法:

public class LoggingInterceptor implements MethodInterceptor 
{ 
    public Object invoke(MethodInvocation methodInvocation) 
    { 
     try 
     { 
      System.out.println("About to call a special method."); 
      Object result = methodInvocation.proceed(); 
      return result; 
     } 
     finally 
     { 
      System.out.println("Finished executing the special method."); 
     } 
    } 
} 

所以我理解的建議(我攔截implement執行)的概念,切入點(這將有方法圍繞他們執行的建議)和切入點顧問(建議和切入點之間的綁定)。

我只是努力在一個簡單的XML配置完全綁定它。

這是我到目前爲止,但我知道它缺少切入點和切入點顧問定義,可能更多。

<beans default-autowire="no" > 
    <bean name="loggingInterceptor" class="org.me.myproject.aop.LoggingInterceptor"/> 
</beans> 

缺少什麼我在這裏,使這個特定的嘶嘶聲:: foo的()和巴茲:: wapap()調用?

任何在正確的方向微調都非常感謝!

回答

5

補充一點:

<aop:config> 
    <aop:advisor advice-ref="loggingInterceptor" pointcut="execution(public * Fizz.foo(..))"/> 
    <aop:advisor advice-ref="loggingInterceptor" pointcut="execution(public * Buzz.wapap(..))"/> 
</aop:config> 

您還需要添加適合於您的框架版本AOP命名空間聲明:

<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" 
     xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
     "> 

還要考慮使用@AspectJ方面看這個問題:Spring: Standard Logging aspect (interceptor)

+0

感謝Tomasz,但它看起來像那些將調用任何Fizz或Buzz方法的日誌攔截器建議。我需要它來指定foo()和wapap()。我也需要添加一個xmlns的東西來處理新的aop標籤? – IAmYourFaja

+0

我編輯了我的答案,看看。 –

+0

所有這些記錄在哪裏?我一直在尋找一些Spring AOP框架的XML模式指南,並找不到任何!另外,如果我有一個ExceptionInterceptor(實現ThrowsAdvice)來處理異常,那該怎麼辦?我如何修改這些切入點字符串以指定任何異常? – IAmYourFaja