2010-08-24 39 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是一个杀手级的特性。