您现在的位置是:首页 >技术杂谈 >【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 的注解,并使用了两个元注解 Retention 和 Target。Retention 表示该注解在运行时保留,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() 方法,从而打印方法的执行时间。
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。





U8W/U8W-Mini使用与常见问题解决
QT多线程的5种用法,通过使用线程解决UI主界面的耗时操作代码,防止界面卡死。...
stm32使用HAL库配置串口中断收发数据(保姆级教程)
分享几个国内免费的ChatGPT镜像网址(亲测有效)
Allegro16.6差分等长设置及走线总结