> 文章列表 > 【Spring】SpringAOP打印被注解的方法的执行时间

【Spring】SpringAOP打印被注解的方法的执行时间

【Spring】SpringAOP打印被注解的方法的执行时间

下面是一个 Java 注解,可以用于打印被注解的方法执行时间

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {
}

这里声明了一个名为 LogExecutionTime 的注解,并使用了两个元注解 RetentionTargetRetention 表示该注解在运行时保留,Target 表示注解适用的目标类型(在本例中是方法)。

下面是一个示例方法,在该方法上使用 LogExecutionTime 注解:

@LogExecutionTime
public void myMethod() {// 执行一些代码
}

最后,需要编写一个切面来处理该注解,并打印方法的执行时间:


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;@Aspect
public class ExecutionTimeLogger {@Around("@annotation(LogExecutionTime)")public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {long startTime = System.currentTimeMillis();Object result = joinPoint.proceed();long endTime = System.currentTimeMillis();System.out.println(joinPoint.getSignature() + " executed in " + (endTime - startTime) + "ms");return result;}}

在上述代码中,ExecutionTimeLogger 类使用了 @Aspect 注解来标识它是一个切面,并使用 @Component 注解把它声明为一个 Spring Bean。

logExecutionTime() 方法是一个切点,表示所有被 LogExecutionTime 注解的方法都会匹配该切点。before()after() 方法分别在切点之前和之后执行,并输出方法的执行时间。

当执行被注解的方法时,AspectJ 将自动处理调用 before()after() 方法,从而打印方法的执行时间。