Spring 框架有两大核心 IoC,AOP。在前面我们已经学习过了 IoC 的相关知识,今天就让我们开始 AOP 的学习。
一、AOP 概述
Aspect Oriented Programming(面向切面编程)。
切面就是指某一类特定问题,所以 AOP 也可以理解为面向特定方法编程。
**AOP 是一种思想,是对某一类事情的集中处理。**Spring AOP 是其中的一种实现方式。
AOP 的作用:在程序运行期间,在不修改源代码的基础上,对已有方法进行增强(无侵入性:解耦)。
二、Spring AOP 快速入门
我们先通过下面的程序体验下 AOP 的开发,并掌握 Spring 中 AOP 的开发步骤。
2.1 引入 AOP 依赖:
在 pom.xml 文件中添加配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.2 编写 AOP 程序:
@Aspect
@Slf4j
@Component
public class TestAspect {
@Around("execution(* com.example.demo.controller.*.*(..))")
public Object demo(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("方法执行前执行");
Object result = joinPoint.proceed();
log.info("方法执行后执行");
return result;
}
}
controller 类:
@RequestMapping("/test")
@RestController
@Slf4j
public class TestController {
@RequestMapping("/t1")
public void test1(){
log.info("我是 test1");
}
}
调用 controller 中的 test1 方法。
结果如下:
对程序进行简单的讲解:
-
@Aspect:标识这是一个切面类。
-
@Around:环绕通知,在目标方法的前后都会被执行。后面的表达式表示对哪些方法进行增强。
-
ProceedingJoinPoint.proceed()让原始方法执行。
整个代码划分为三部分。

通过上面的程序,我们也可以感受到 AOP 面向切面编程的一些优势:
- 代码无侵入:不修改原始的业务方法,就可以对原始的业务方法进行了功能的增强或者是功能的改变。
- 减少了重复代码。
- 提高开发效率。
- 维护方便。
三、Spring AOP 详解
3.1 Spring AOP 核心概念:
3.1.1 切点(Pointcut):
切点(Pointcut),也称之为"切入点"。
Pointcut 的作用就是提供一组规则(使用 AspectJ pointcut expression language 来描述),告诉程序对哪些方法来进行功能增强。