pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
代码
创建注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义的注解 * @MethodExecutionTime */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodExecutionTime { }
AOP拦截注解
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; /** * 被@MethodExecutionTime注解的方法计算其执行时间并输出 */ @Aspect @Component public class MethodExecutionTimeAspect { @Around("@annotation(com.*.annotation.MethodExecutionTime)") public Object logMethodExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { String methodName = joinPoint.getSignature().getName(); long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long endTime = System.currentTimeMillis(); System.out.println("Method: " + methodName + " Execution Time: " + (endTime - startTime) + " milliseconds"); return result; } }
使用
将@MethodExecutionTime用在Service、Component等呗spring容器托管的bean的方法上。实现方法执行时间的监测