1.什么是 Spring AOP?
AOP(面向切面编程)是一种对一类问题集中处理的思想,比如拦截器、统一返回结果管理、统一异常处理、登录校验等。如果使用 OOP(面向对象编程),相同的代码会重复多次出现,业务方法中混杂着非核心的逻辑。
Spring AOP就是为了解决这些问题存在,是 AOP 思想的其中一种实现方式。
2.Spring AOP 优点与上手
优点:
- 不影响原有代码,解耦
- 便于维护功能
- 提高开发效率
- 减少重复代码
快速上手 Spring AOP
编写一个使用 Spring AOP 计算所有方法的运行时长的例子。
- 在 pom.xml 文件引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
注意:SpringBoot 使用版本号为 3.x.x,AOP 依赖需要添加版本号。
- 编写 AOP 程序
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.*.*(..))") // 该注解 () 中是要执行方法的路径
// 参数部分的 ProceedingJoinPoint joinPoint 即要执行的方法
// 不确定执行方法的返回类型,因此在这里设返回类型为 Object
public Object timeRecord(ProceedingJoinPoint joinPoint) Throwable {
System.currentTimeMillis();
joinPoint.proceed();
System.currentTimeMillis();
log.info(joinPoint.getSignature() + + (end - start) + );
proceed;
}
}

