利用Spring注解方式实现AOP,记录指定的方法执行所需的时间

254 阅读1分钟

利用Spring注解方式实现AOP,使用AOP环绕通知的方式,记录方法执行前和执行后的时间,两个时间相减得到的就是方法执行所需的时间。

实现代码入下,超简单:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class TestCost {
    // 定义切点,拦截所有满足条件的方法
    @Pointcut("execution(public * gov.hkpf.hkplic.struts.action.SPP.*.search*(..))")
    public void point() {
    }

    @Around(value="TestCost.point()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        try{
            return joinPoint.proceed();
        } finally {
            System.out.println(joinPoint.getTarget());
            System.out.println(joinPoint.getArgs());
            System.out.println(joinPoint.getSignature() + " cost: " + (System.currentTimeMillis() - start));
        }
    }

}