AOP的基本应用案例---统计每个函数的执行时间
1.导入依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.准备好要计算的SpringBoot的项目(本案例以service的实现类为例)
3.编写AOP的代码:
package com.itheima.aop;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//标时当前的类是一个AOP类
@Component
public class RecordTimeAspect {@Around("execution(* com.itheima.service.impl.*.*(..))")public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {//1.记录方法开始时的时间long begin = System.currentTimeMillis();//2.执行原始的方法Object result = pjp.proceed();//3.记录方法结束的时间long end = System.currentTimeMillis();log.info("方法{}执行耗时:{}ms",pjp.getSignature(),end-begin);return result;}
}
4.执行结果: