面向切面编程(Aspect-Oriented Programming,AOP)。在系统运行时动态添加代码的方式称为面向切面编程(AOP)。
相关概念
Joinpoint
(连接点):类里面可以被增强的方法即为连接点。例如,想修改哪个方法的功能, 那么该方法就是一个连接点。Pointcut
(切入点):对 Joinpoint 进行拦截的定义即为切入点,例如,拦截所有以 insert 开始的方法,这个定义即为切入点。Advice
(通知):拦截到 Joinpoint 之后所要做的事情就是通知。例如, 打印日志监控。 通知分为前置通知、后置通知、异常通知、最终通知和环绕通知。Aspect
(切面): Pointcut 和 Advice 的结合。Target
(目标对象):要增强的类称为 Target。
Spring Boot 项目中使用 AOP
SpringBoot 在 Spring 的基础上对 AOP 的配置提供了自动化配置解决方案 spring-boot-starter-aop
。配置步骤如下。:
- 首先在 Spring Boot Web 项目中引入
spring-boot-starter-aop
依赖,代码如下:
<!-- spring aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
- 创建 UserService 类,代码如下:
import org.springframework.stereotype.Service;
@Service
public class UserService {
public String getUserById(Integer id) {
System