2010-08-24 94 views
1

我需要在項目中的某些包中記錄很多類,我無法更改其源代碼。 所以我需要一個解決方案,我可以指定包名稱,並與春天aop添加日誌記錄到該包的類沒有改變他們,但我不知道我該怎麼做。 我該怎麼做?按包名彈出日誌記錄

回答

1

使用Spring AOP時,如果它們被用作Spring Beans,那麼只能記錄這些類,即使這樣您也只能記錄公共方法執行。

這裏是@AspectJ通知(這是與「真正的AspectJ」和Spring AOP兼容的樣式,閱讀有關區別in the spring reference)的一個方面,您可以在Spring AOP和AspectJ字節碼編織中使用它:

@Aspect 
public class LoggingAspect{ 

    @Pointcut("execution(* com.mycompany.myproject.*.*(..))") 
    public void methodToLog(){ 
    }; 

    @Around("methodToLog()") 
    public Object logMethod(final ProceedingJoinPoint joinPoint) throws Throwable{ 
     final StaticPart staticPart = joinPoint.getStaticPart(); 
     final String sig = 
      "" + staticPart.getSignature() + " with args: " 
       + Arrays.deepToString(joinPoint.getArgs()); 
     System.out.println("Entering method " + sig); 
     final Object result = joinPoint.proceed(); 
     System.out.println("Leaving method " + sig); 
     return result; 
    } 

} 

這是一個愚蠢的類的一些方法:

package com.mycompany.myproject; 
public class Dummy1{ 

    public static void main(final String[] args){ 
     final Dummy1 dummy = new Dummy1(); 
     dummy.doSomeStuff(); 
     dummy.doSomeStuffWithSomeArgs("Hello", 123); 
    } 

    private void doSomeStuff(){} 

    public void doSomeStuffWithSomeArgs(final String firstArg, 
     final int secondArg){} 

} 

當你開始這個類在Eclipse/AJDT如Java/AspectJ的應用程序,你會得到以下輸出:

Entering method void com.mycompany.myproject.Dummy1.main(String[]) with args: [[]] 
Entering method void com.mycompany.myproject.Dummy1.doSomeStuff() with args: [] 
Leaving method void com.mycompany.myproject.Dummy1.doSomeStuff() with args: [] 
Entering method void com.mycompany.myproject.Dummy1.doSomeStuffWithSomeArgs(String, int) with args: [Hello, 123] 
Leaving method void com.mycompany.myproject.Dummy1.doSomeStuffWithSomeArgs(String, int) with args: [Hello, 123] 
Leaving method void com.mycompany.myproject.Dummy1.main(String[]) with args: [[]] 

要在Spring中測試這個AOP會涉及更多的工作(主要的方法不行,你將不得不創建一個ApplicationContext並註冊一個Dummy1類型的bean,你將在其中調用這個方法),所以我會把它留給你,但我很確定私人方法調用不會被記錄。

如果你下載的SpringSource Tool Suite,你得到的方面可視化和測試好的工具。即使您只想使用Spring AOP,也應該閱讀AspectJ book。這是一本很棒的書。


順便說一句:你顯然想使用一個真正的記錄器,而不是system.out。您可以爲每個方面定義一個方面,或者(僅限於真實的aspectj),您可以將其作爲目標類中的靜態成員引入,以獲取每個類的日誌記錄。在我看來,AspectJ是一個殺手級的特性。