2009-01-18 62 views
4

爲了使用Spring AOP實現Logging,我遵循了以下簡單的步驟。但它似乎不起作用。任何幫助將是非常有用切入點不能與Spring AOP一起使用

1)創建MyLoggingAspect創建一個類(TixServiceImpl)類

import org.aspectj.lang.ProceedingJoinPoint; 

public class MyLoggingAspect 
{ 

    public MyLoggingAspect() { 
     super(); 
     System.out.println("Instantiated MyLoggingAspect");  
    } 

    public Object log(ProceedingJoinPoint call) throws Throwable 
    { 
     System.out.println("from logging aspect: entering method [" + call.toShortString() 
          +"] with param:"+call.getArgs()[0]); 

     Object point = call.proceed(); 

     System.out.println("from logging aspect: exiting method [" + call.toShortString() 
          + "with return as:" +point);   

     return point; 
    } 

}

2),我想記錄

public class TixServiceImpl implements TixService{ 

    @Override 
    public void calculateSomething() { 
     String s = "did some calculation.."; 
     System.out.println(s); 
    } 

    @Override 
    public String getTixName() { 
     return null; 
    } 
} 

3 )創建了spring-aspectj.xml文件

<beans...  
    <bean id="LoggingAspect" class = "MyLoggingAspect"/> 
    <aop:config> 
      <aop:aspect ref="LoggingAspect"> 
      <aop:pointcut id="myCutLogging" 
        expression="execution(* TixService*.*(..))"/> 
      <aop:around pointcut-ref="myCutLogging" method="log"/> 
      </aop:aspect> 
    </aop:config>  
</beans> 

4)創建了一個簡單的測試客戶端(TixClient

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.FileSystemXmlApplicationContext; 

public class TixClient { 

    public static void main(String[] a){ 

     ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring-aspectj.xml"); 

     TixService tix = new TixServiceImpl(); 
     tix.calculateSomething(); 
     String s = tix.getTixName(); 

     System.out.println("End of the the client invocation!!"); 
    } 
} 

5)它給了我下面的輸出

... 
Instantiated MyLoggingAspect 
did some calculation.. 
End of the the client invocation!! 

回答

14

我只是檢查你的代碼,但我有一個預感問題是,你沒有得到你的來自Spring的TixServiceImpl實例,而是你自己在你的TixClient中手動實例化它。我認爲你的TixService需要是Spring ApplicationContext獲得的Spring bean,以便Spring有機會在返回的實例上設置方面。

+0

感謝您的提示,它的工作。如果在線提供的示例/示例/教程中提到了這將是一件好事。 – 2009-01-19 03:38:25

+0

很高興能有幫助 – 2009-01-19 05:45:55

2

Scott Bale是對的:讓春天爲你提供TixServiceImpl。同樣在這種情況下,啓用彈簧日誌記錄可能會有所幫助,因爲它會告訴您找到了某個方面/設備的多少個目標。