Spring AOP 核心原理与实战指南
什么是 Spring AOP
AOP(面向切面编程)是一种对一类问题集中处理的思想,比如拦截器、统一返回结果管理、统一异常处理、登录校验等。如果使用传统的 OOP(面向对象编程),相同的代码容易重复出现,业务方法中混杂着非核心的逻辑。
Spring AOP 是 AOP 思想在 Spring 框架中的一种实现方式,旨在解决上述解耦和维护难题。
核心优势
- 无侵入:不影响原有代码结构
- 高解耦:将横切关注点从业务逻辑中分离
- 易维护:功能修改集中在切面类中
- 提效率:减少重复代码编写
快速上手
1. 引入依赖
在 pom.xml 中添加 AOP 支持依赖。注意确保 Spring Boot 版本与依赖兼容。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 编写切面类
下面是一个计算所有方法运行时长的小例子。我们创建一个 Aspect 类,利用 @Around 注解包裹目标方法。
package com.example.springbookdemo.aspect;
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
@Component
public class TimeRecordAspect {
@Around("execution(* com.example.springbookdemo.controller.*.*(..))")
public Object timeRecord(ProceedingJoinPoint joinPoint) throws Throwable {
System.currentTimeMillis();
joinPoint.proceed();
System.currentTimeMillis();
log.info(joinPoint.getSignature() + + (end - start) + );
proceed;
}
}

