一、 什么是AOP
Spring Boot 的 AOP(Aspect-Oriented Programming,面向切面编程) 是 Spring 框架中的一个核心模块,用于处理系统中分散的 横切关注点(如日志、事务、权限校验等)。它通过将通用功能与业务逻辑解耦,提高代码的可维护性和复用性。
使用方法
@Aspect
@Component
public class LogAspect {
// 定义切点:匹配 service 包下所有方法
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {}
// 前置通知
@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("方法执行前:" + joinPoint.getSignature().getName());
}
// 环绕通知(控制方法执行)
@Around("serviceMethods()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed(); // 执行目标方法
long duration = System.currentTimeMillis() - start;
System.out.println("方法执行耗时:" + duration + "ms");
return result;
}
}