使用注释跟踪执行

时间:2010-12-14 02:21:38

标签: java debugging annotations tracing

有没有办法告诉Java通过用注释标记它们来跟踪某些函数?我希望能够做到这一点:

class Foo {

    @trace
    int foo(int bar) {
        return bar + 5;
    }
}

然后,如果启用了跟踪,我会得到:

  

**输入foo(5)

     

** foo返回:10

2 个答案:

答案 0 :(得分:1)

你可以使用spring aop,使用@Around annotations

来做到这一点

如何实施AOP记录:

将此添加到applicationContext.xml

 <aop:aspectj-autoproxy/>
  <context:annotation-config/>
  <context:component-scan base-package="com.company.*"/>

在com.company。* package中创建以下类:

package com.company.*;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Aspect
public class AOPMethodLogger {

    @Around("bean(*Service)")
    public Object timeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object retVal = joinPoint.proceed();
        stopWatch.stop();
        if(stopWatch.getTotalTimeMillis() > 35){
            StringBuffer logMessageStringBuffer = new StringBuffer();
            logMessageStringBuffer.append(joinPoint.getTarget().getClass().getName());
            logMessageStringBuffer.append(".");
            logMessageStringBuffer.append(joinPoint.getSignature().getName());
            logMessageStringBuffer.append("(");
            logMessageStringBuffer.append(joinPoint.getArgs());
            logMessageStringBuffer.append(")");
            logMessageStringBuffer.append(" execution time: ");
            logMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
            logMessageStringBuffer.append(" ms");
            System.out.println(logMessageStringBuffer.toString());
        }
        return retVal;
    }

}

答案 1 :(得分:1)

您无需使用名为InTrace的工具添加注释即可完成此操作。

注意:InTrace是我编写的免费开源工具。