1、创建一个自定义注解 @LogExecutionTime
package com.base.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
2、创建一个切面类 LoggingAspect
,在该类中编写记录执行时间的逻辑
package com.base.annotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class LoggingAspect {
@Around("@annotation(com.unisic.base.annotation.LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - startTime;
log.info(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed;
}
}
3、在需要记录执行时间的方法上添加 @LogExecutionTime
注解,代码示例
@Service
public class MyService {
@LogExecutionTime
public void performDatabaseQuery() {
// 执行数据库查询操作
}
}