SpringBoot下使用AOP做日志
AOP实现接口执行时间的计算:
- SpringBoot项目导入spring-boot-starter-aop依赖
- 编写切面类
- 类上加@Aspect注解,表明这是一个切面类
- 类上加@Component,把切面交给Spring管理(我们要切的Controller/Service都是Spring容器的,切面要对它们起作用,就必须同样进入容器)
- 类内部配置切点表达式,比如@Pointcut("execution(* com.bravo.demo.controller.*.*(..))") 表示对com.bravo.demo.controller包下所有方法进行增强
- 类内部编写增强逻辑,通常使用@Before、@Around声明这是一个增强,不同的注解增强的方式不同,比如@Before前置增强、@Around环绕增强
1、导入AOP整合SpringBoot依赖
org.springframework.boot spring-boot-starter-aop
2、编写切面类:com.zhixi.config.aop.ApiTimeLogAspect
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @ClassName ApiTimeLogAspect
* @Author zhangzhixi
* @Description
* @Date 2022-4-15 10:42
* @Version 1.0
*/
@Slf4j
/*第一步:声明这是一个切面类*/
@Aspect
@Component
public class ApiTimeLogAspect {
/**
* 第二步:定义切点表达式,明确要对那些方法起作用(比如,只对com.bravo.demo.controller包的方法计算接口耗时)
*/
@Pointcut("execution(* com.zhixi.controller.*.*(..))")
public void controllerPointcut() {
}
/**
* 第三步:1.通过引用切点表达式,明确这个增强的应用规则。 2.编写增强逻辑
*
* @param proceedingJoinPoint 执行目标方法的参数
* @return 返回目标方法的执行结果
* @throws Throwable proceedingJoinPoint.proceed()方法抛出的异常
*/
@Around(value = "controllerPointcut()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// 记录接口执行前的时间戳
long startTime = System.currentTimeMillis();
// 实际执行目标方法,类似动态代理的invoke()执行目标方法
Object result = proceedingJoinPoint.proceed();
// 计算接口耗时
log.info("------------ 耗时: {} ms ------------", System.currentTimeMillis() - startTime);
// 只做增强不做改变,还是要把接口原本的结果返回
return result;
}
}
3、启动项目访问接口即可