文章目录
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 {