1. 一、AOP 到底是什么?

AOP = 面向切面编程 = 不修改源代码,给方法统一加功能

比如:

  • 统一日志
  • 统一权限校验
  • 统一接口耗时统计
  • 统一异常处理
  • 统一事务
  • 统一缓存

这些横切逻辑,不用每个方法都写,AOP 一次性全部搞定。

二、AOP 核心名词(必须懂)

  • 切面(Aspect):你写的增强类(日志、权限等)
  • 切点(Pointcut):你要增强哪些方法(匹配规则)
  • 通知(Advice):增强的代码(什么时候执行)
  • 连接点(JoinPoint):被增强的方法
  • 目标对象(Target):被增强的类

三、Spring AOP 5 种通知(核心)

  1. @Before:方法执行前
  2. @After:方法执行后(无论成功失败)
  3. @AfterReturning:方法正常返回后
  4. @AfterThrowing:方法抛异常后
  5. @Around:环绕通知(最强大,前后都能控制

四、SpringBoot 快速使用 AOP(步骤)

1)引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2)开启 AOP(SpringBoot 默认开启,可不写)

@EnableAspectJAutoProxy // 可选
@SpringBootApplication
public class Application {}

五、实战案例

实战案例1:统一接口日志(最常用)

① 创建切面类

@Slf4j
@Aspect
@Component
public class LogAspect {

    // 1. 定义切点:匹配所有 controller 方法
    @Pointcut("execution(* com.xxx.controller..*.*(..))")
    public void logPointcut() {}

    // 2. 环绕通知:最常用
    @Around("logPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行前
        long start = System.currentTimeMillis();
        log.info("请求开始:{}", joinPoint.getSignature());

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 执行后
        long end = System.currentTimeMillis();
        log.info("请求结束,耗时:{}ms", end - start);
        return result;
    }
}

效果:所有 Controller 方法自动打印请求、响应、耗时。

实战案例 2:方法执行前校验权限

@Before("logPointcut()")
public void before(JoinPoint joinPoint) {
    log.info("权限校验中...");
    // 你可以写权限逻辑
}

实战案例 3:方法抛异常时统一处理

@AfterThrowing(pointcut = "logPointcut()", throwing = "e")
public void afterThrow(Exception e) {
    log.error("方法异常:" + e.getMessage());
}

六、切点表达式(最重要)

格式:

execution( 返回值  包名.类名.方法名(参数) )

最常用写法:

1、匹配所有 Controller

execution(* com.xxx.controller..*.*(..))

2、匹配所有 Service

execution(* com.xxx.service..*.*(..))

3、匹配某个注解(超级实用)

给方法加 @Log 就增强:

@Pointcut("@annotation(com.xxx.annotation.Log)")

七、AOP 最强大:@Around 环绕通知

它可以控制:是否执行、修改参数、修改返回值、捕获异常

@Around("pointcut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
    // 前
    Object result = pjp.proceed(); // 执行目标方法
    // 后
    return result;
}

八、AOP 常见使用场景(企业 90% 都在用)

  • 接口日志统一输出
  • 接口耗时统计
  • 全局权限校验
  • 全局异常捕获
  • 多数据源切换
  • 事务管理(@Transactional)
  • 缓存控制
  • 分布式锁
  • 幂等性校验
  • API 限流

九、AOP 常见坑(必须避坑)

  • 同类方法调用不生效(this. 方法 () 不走代理)解决:自己注入自己调用
  • 私有方法不生效AOP 只增强 public
  • 静态方法不生效
  • 加了 @Async 等注解可能冲突用 @Order 控制顺序
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐