十一、Spring AOP
十一、Spring AOP
- 1. AOP概述
- 2. Spring AOP快速⼊⻔
- 2.1 引⼊AOP依赖
- 2.2 编写AOP程序
- 3. Spring AOP 详解
- 3.1 Spring AOP核⼼概念
- 3.1.1 切点(Pointcut) @Around 哪个包
- 3.1.2 连接点(Join Point) 包下面的方法
- 3.1.3 通知(Advice) 就是要执行的方法
- 3.1.4 切⾯(Aspect)
- 3.2 通知类型
- 3.3 @PointCut
- 3.4 切⾯优先级 @Order
- 3.5 切点表达式
- 3.5.1 execution表达式
- 3.5.2 @annotation
本节⽬标
- 了解AOP的概念
- 学习Spring AOP的实现⽅式以及实现原理, 对代理模式有⼀定了解
1. AOP概述
学习完Spring的统⼀功能之后, 我们进⼊到AOP的学习. AOP是Spring框架的第⼆⼤核⼼(第⼀⼤核⼼是IoC)
- 什么是AOP?
- Aspect Oriented Programming(⾯向切⾯编程)
什么是⾯向切⾯编程呢? 切⾯就是指某⼀类特定问题, 所以AOP也可以理解为⾯向特定⽅法编程.
什么是⾯向特定⽅法编程呢? ⽐如上个章节学习的"登录校验", 就是⼀类特定问题. 登录校验拦截器, 就是对"登录校验"这类问题的统⼀处理. 所以, 拦截器也是AOP的⼀种应⽤. AOP是⼀种思想, 拦截器是AOP思想的⼀种实现. Spring框架实现了这种思想, 提供了拦截器技术的相关接⼝.
同样的, 统⼀数据返回格式和统⼀异常处理, 也是AOP思想的⼀种实现.
简单来说: AOP是⼀种思想, 是对某⼀类事情的集中处理.
什么是Spring AOP?
AOP是⼀种思想, 它的实现⽅法有很多, 有Spring AOP,也有AspectJ、CGLIB等.
Spring AOP是其中的⼀种实现⽅式.
学会了统⼀功能之后, 是不是就学会了Spring AOP呢, 当然不是.
拦截器作⽤的维度是URL(⼀次请求和响应), @ControllerAdvice 应⽤场景主要是全局异常处理(配合⾃定义异常效果更佳), 数据绑定, 数据预处理. AOP作⽤的维度更加细致(可以根据包、类、⽅法名、参数等进⾏拦截), 能够实现更加复杂的业务逻辑.
举个例⼦:
我们现在有⼀个项⽬, 项⽬中开发了很多的业务功能
现在有⼀些业务的执⾏效率⽐较低, 耗时较⻓, 我们需要对接⼝进⾏优化.
第⼀步就需要定位出执⾏耗时⽐较⻓的业务⽅法, 再针对该业务⽅法来进⾏优化
如何定位呢? 我们就需要统计当前项⽬中每⼀个业务⽅法的执⾏耗时.
如何统计呢? 可以在业务⽅法运⾏前和运⾏后, 记录下⽅法的开始时间和结束时间, 两者之差就是这个⽅法的耗时
这种⽅法是可以解决问题的, 但⼀个项⽬中会包含很多业务模块, 每个业务模块⼜有很多接⼝, ⼀个接⼝⼜包含很多⽅法, 如果我们要在每个业务⽅法中都记录⽅法的耗时, 对于程序员⽽⾔, 会增加很多的⼯作量
AOP就可以做到在不改动这些原始⽅法的基础上, 针对特定的⽅法进⾏功能的增强.
AOP的作⽤:在程序运⾏期间在不修改源代码的基础上对已有⽅法进⾏增强(⽆侵⼊性: 解耦)
接下来我们来看Spring AOP如何来实现
2. Spring AOP快速⼊⻔
学习什么是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程序
记录Controller中每个⽅法的执⾏时间
@Slf4j
@Aspect
@Component
public class TimeAspect {/*** 记录⽅法耗时*/@Around("execution(* com.example.demo.controller.*.*(..))")public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {//记录⽅法执⾏开始时间long begin = System.currentTimeMillis();//执⾏原始⽅法Object result = pjp.proceed();//记录⽅法执⾏结束时间long end = System.currentTimeMillis();//记录⽅法执⾏耗时log.info(pjp.getSignature() + "执⾏耗时: {}ms", end - begin);return result;}
}
运⾏程序, 观察⽇志
对程序进⾏简单的讲解:
- @Aspect: 标识这是⼀个切⾯类
- @Around: 环绕通知, 在⽬标⽅法的前后都会被执⾏. 后⾯的表达式表⽰对哪些⽅法进⾏增强.
- ProceedingJoinPoint.proceed() 让原始⽅法执⾏
整个代码划分为三部分
我们通过AOP⼊⻔程序完成了业务接⼝执⾏耗时的统计.
通过上⾯的程序, 我们也可以感受到AOP⾯向切⾯编程的⼀些优势:
• 代码⽆侵⼊: 不修改原始的业务⽅法, 就可以对原始的业务⽅法进⾏了功能的增强或者是功能的改变
• 减少了重复代码
• 提⾼开发效率
• 维护⽅便
3. Spring AOP 详解
下⾯我们再来详细学习AOP, 主要是以下⼏部分
• Spring AOP中涉及的核⼼概念
• Spring AOP通知类型
• 多个AOP程序的执⾏顺序
3.1 Spring AOP核⼼概念
3.1.1 切点(Pointcut) @Around 哪个包
切点(Pointcut), 也称之为"切⼊点"
Pointcut 的作⽤就是提供⼀组规则 (使⽤ AspectJ pointcut expression language 来描述), 告诉程序对哪些⽅法来进⾏功能增强.
上⾯的表达式 execution(* com.example.demo.controller.*.*(..)) 就是切点表达式.
3.1.2 连接点(Join Point) 包下面的方法
满⾜切点表达式规则的⽅法, 就是连接点. 也就是可以被AOP控制的⽅法
以⼊⻔程序举例, 所有 com.example.demo.controller 路径下的⽅法, 都是连接点.
上述BookController 中的⽅法都是连接点
切点和连接点的关系
连接点是满⾜切点表达式的元素. 切点可以看做是保存了众多连接点的⼀个集合.
⽐如:
切点表达式: 全体教师
连接点就是: 张三,李四等各个⽼师
3.1.3 通知(Advice) 就是要执行的方法
通知就是具体要做的⼯作, 指哪些重复的逻辑,也就是共性功能(最终体现为⼀个⽅法)
⽐如上述程序中记录业务⽅法的耗时时间, 就是通知
在AOP⾯向切⾯编程当中, 我们把这部分重复的代码逻辑抽取出来单独定义, 这部分代码就是通知的内容
3.1.4 切⾯(Aspect)
切⾯(Aspect) = 切点(Pointcut) + 通知(Advice)
通过切⾯就能够描述当前AOP程序需要针对于哪些⽅法, 在什么时候执⾏什么样的操作
切⾯既包含了通知逻辑的定义, 也包括了连接点的定义
切⾯所在的类, 我们⼀般称为切⾯类(被@Aspect注解标识的类
3.2 通知类型
上⾯我们讲了什么是通知, 接下来学习通知的类型. @Around 就是其中⼀种通知类型, 表⽰环绕通知.
Spring中AOP的通知类型有以下⼏种:
• @Around: 环绕通知, 此注解标注的通知⽅法在⽬标⽅法前, 后都被执⾏
• @Before: 前置通知, 此注解标注的通知⽅法在⽬标⽅法前被执⾏
• @After: 后置通知, 此注解标注的通知⽅法在⽬标⽅法后被执⾏, ⽆论是否有异常都会执⾏
• @AfterReturning: 返回后通知, 此注解标注的通知⽅法在⽬标⽅法后被执⾏, 有异常不会执⾏
• @AfterThrowing: 异常后通知, 此注解标注的通知⽅法发⽣异常后执⾏
接下来我们通过代码来加深对这⼏个通知的理解:
@Slf4j
@Aspect
@Component
public class AspectDemo {//前置通知@Before("execution(* com.example.demo.controller.*.*(..))")public void doBefore() {log.info("执⾏ Before ⽅法");}//后置通知@After("execution(* com.example.demo.controller.*.*(..))")public void doAfter() {log.info("执⾏ After ⽅法");}//返回后通知@AfterReturning("execution(* com.example.demo.controller.*.*(..))")public void doAfterReturning() {log.info("执⾏ AfterReturning ⽅法");}//抛出异常后通知@AfterThrowing("execution(* com.example.demo.controller.*.*(..))")public void doAfterThrowing() {log.info("执⾏ doAfterThrowing ⽅法");}//添加环绕通知@Around("execution(* com.example.demo.controller.*.*(..))")public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {log.info("Around ⽅法开始执⾏");Object result = joinPoint.proceed();log.info("Around ⽅法结束执⾏");return result;}
}
@RequestMapping("/test")
@RestController
public class TestController {@RequestMapping("/t1")public String t1() {return "t1";}@RequestMapping("/t2")public boolean t2() {int a = 10 / 0;return true;}
}
运⾏程序, 观察⽇志:
- 正常运⾏的情况
http://127.0.0.1:8080/test/t1
程序正常运⾏的情况下, @AfterThrowing 标识的通知⽅法不会执⾏
从上图也可以看出来, @Around 标识的通知⽅法包含两部分, ⼀个"前置逻辑", ⼀个"后置逻辑".其中"前置逻辑" 会先于 @Before 标识的通知⽅法执⾏, “后置逻辑” 会晚于 @After 标识的通知⽅法执⾏
2. 异常时的情况
http://127.0.0.1:8080/test/t2
程序发⽣异常的情况下:
- @AfterReturning 标识的通知⽅法不会执⾏
- @AfterThrowing 标识的通知⽅法执⾏了
- @Around 环绕通知中原始⽅法调⽤时有异常,通知中的环绕后的代码逻辑也不会在执⾏了(因为原始⽅法调⽤出异常了)
注意事项:
• @Around 环绕通知需要调⽤ ProceedingJoinPoint.proceed() 来让原始⽅法执⾏, 其他
通知不需要考虑⽬标⽅法执⾏.
• @Around 环绕通知⽅法的返回值, 必须指定为Object, 来接收原始⽅法的返回值, 否则原始⽅法执
⾏完毕, 是获取不到返回值的.
• ⼀个切⾯类可以有多个切点
3.3 @PointCut
上⾯代码存在⼀个问题, 就是存在⼤量重复的切点表达式 execution(* com.example.demo.controller..(…)) , Spring提供了 @PointCut 注解, 把公共的切点表达式提取出来, 需要⽤到时引⽤该切⼊点表达式即可.
上述代码就可以修改为
@Slf4j
@Aspect
@Component
public class AspectDemo {//定义切点(公共的切点表达式)@Pointcut("execution(* com.example.demo.controller.*.*(..))")private void pt(){}//前置通知@Before("pt()")public void doBefore() {//...代码省略}//后置通知@After("pt()")public void doAfter() {//...代码省略}//返回后通知@AfterReturning("pt()")public void doAfterReturning() {//...代码省略}//抛出异常后通知@AfterThrowing("pt()")public void doAfterThrowing() {//...代码省略}//添加环绕通知@Around("pt()")public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {//...代码省略}
}
当切点定义使⽤private修饰时, 仅能在当前切⾯类中使⽤, 当其他切⾯类也要使⽤当前切点定义时, 就需要把private改为public. 引⽤⽅式为: 全限定类名.⽅法名()
@Slf4j
@Aspect
@Component
public class AspectDemo2 {//前置通知@Before("com.example.demo.aspect.AspectDemo.pt()")public void doBefore() {log.info("执⾏ AspectDemo2 -> Before ⽅法");}
}
3.4 切⾯优先级 @Order
当我们在⼀个项⽬中, 定义了多个切⾯类时, 并且这些切⾯类的多个切⼊点都匹配到了同⼀个⽬标⽅法.
当⽬标⽅法运⾏的时候, 这些切⾯类中的通知⽅法都会执⾏, 那么这⼏个通知⽅法的执⾏顺序是什么样的呢?
我们还是通过程序来求证:
定义多个切⾯类
为防⽌⼲扰, 我们把AspectDemo这个切⾯先去掉(把@Component 注解去掉就可以)
为简单化, 只写了 @Before 和 @After 两个通知
@Component
public class AspectDemo2 {@Pointcut("execution(* com.example.demo.controller.*.*(..))")private void pt(){}//前置通知@Before("pt()")public void doBefore() {log.info("执⾏ AspectDemo2 -> Before ⽅法");}//后置通知@After("pt()")public void doAfter() {log.info("执⾏ AspectDemo2 -> After ⽅法");}
}
@Component
public class AspectDemo3 {@Pointcut("execution(* com.example.demo.controller.*.*(..))")private void pt(){}//前置通知@Before("pt()")public void doBefore() {log.info("执⾏ AspectDemo3 -> Before ⽅法");}//后置通知@After("pt()")public void doAfter() {log.info("执⾏ AspectDemo3 -> After ⽅法");}
}
@Component
public class AspectDemo4 {@Pointcut("execution(* com.example.demo.controller.*.*(..))")private void pt(){}//前置通知@Before("pt()")public void doBefore() {log.info("执⾏ AspectDemo4 -> Before ⽅法");}//后置通知@After("pt()")public void doAfter() {log.info("执⾏ AspectDemo4 -> After ⽅法");}
}
通过上述程序的运⾏结果, 可以看出:
存在多个切⾯类时, 默认按照切⾯类的类名字⺟排序:
• @Before 通知:字⺟排名靠前的先执⾏
• @After 通知:字⺟排名靠前的后执⾏
但这种⽅式不⽅便管理, 我们的类名更多还是具备⼀定含义的.
Spring 给我们提供了⼀个新的注解, 来控制这些切⾯通知的执⾏顺序: @Order
使⽤⽅式如下
通过上述程序的运⾏结果, 得出结论:
@Order 注解标识的切⾯类, 执⾏顺序如下:
• @Before 通知:数字越⼩先执⾏
• @After 通知:数字越⼤先执⾏
@Order 控制切⾯的优先级, 先执⾏优先级较⾼的切⾯, 再执⾏优先级较低的切⾯, 最终执⾏⽬标⽅法
3.5 切点表达式
上⾯的代码中, 我们⼀直在使⽤切点表达式来描述切点. 下⾯我们来介绍⼀下切点表达式的语法.
切点表达式常⻅有两种表达⽅式
- execution(RR):根据⽅法的签名来匹配
- @annotation(RR) :根据注解匹配
3.5.1 execution表达式
execution() 是最常⽤的切点表达式, ⽤来匹配⽅法, 语法为:
execution(<访问修饰符> <返回类型> <包名.类名.⽅法(⽅法参数)> <异常>)
其中: 访问修饰符和异常可以省略
切点表达式⽀持通配符表达:
1. * :匹配任意字符,只匹配⼀个元素(返回类型, 包, 类名, ⽅法或者⽅法参数)a. 包名使⽤ * 表⽰任意包(⼀层包使⽤⼀个*)b. 类名使⽤ * 表⽰任意类c. 返回值使⽤ * 表⽰任意返回值类型d. ⽅法名使⽤ * 表⽰任意⽅法e. 参数使⽤ * 表⽰⼀个任意类型的参数
2. .. :匹配多个连续的任意符号, 可以通配任意层级的包, 或任意类型, 任意个数的参数a. 使⽤ .. 配置包名,标识此包以及此包下的所有⼦包b. 可以使⽤ .. 配置参数,任意个任意类型的参数
切点表达式⽰例
- TestController 下的 public修饰, 返回类型为String ⽅法名为t1, ⽆参⽅法
execution(public String com.example.demo.controller.TestController.t1())
- 省略访问修饰符
execution(String com.example.demo.controller.TestController.t1())
匹配所有返回类型
execution(* com.example.demo.controller.TestController.t1())
匹配TestController 下的所有⽆参⽅法
execution(* com.example.demo.controller.TestController.*())
匹配TestController 下的所有⽅法
execution(* com.example.demo.controller.TestController.*(..))
匹配controller包下所有的类的所有⽅法
execution(* com.example.demo.controller.*.*(..))
匹配所有包下⾯的TestController
execution(* com..TestController.*(..))
匹配com.example.demo包下, ⼦孙包下的所有类的所有⽅法
execution(* com.example.demo..*(..))
Spring AOP 中的切点表达式用于指定在哪些地方应该应用切面逻辑。下面我将分别介绍两种常用的切点表达式,并给出详细的案例代码。
- execution(RR):根据方法的签名来匹配
- 通过 execution() 表达式可以匹配到程序执行的连接点,其中 RR 为方法的返回类型。可以使用通配符 * 匹配任意字符,使用 … 匹配任意数量的参数。
- 例如,execution(* com.example.service..(…)) 表示匹配 com.example.service 包下的所有类的所有方法。
@Aspect
@Component
public class LoggingAspect {@Before("execution(* com.example.service.*.*(..))")public void logBefore(JoinPoint joinPoint) {System.out.println("Before executing method: " + joinPoint.getSignature());}@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")public void logAfterReturning(JoinPoint joinPoint, Object result) {System.out.println("After returning from method: " + joinPoint.getSignature() + ", result: " + result);}
}
- @annotation(RR):根据注解匹配
- 通过 @annotation() 表达式可以匹配到带有特定注解的连接点,其中 RR 为注解的类型。
- 例如,@annotation(org.springframework.transaction.annotation.Transactional) 表示匹配所有使用 @Transactional 注解的方法。
@Aspect
@Component
public class TransactionAspect {@Before("@annotation(org.springframework.transaction.annotation.Transactional)")public void beforeTransaction(JoinPoint joinPoint) {System.out.println("Before transactional method: " + joinPoint.getSignature());}@After("@annotation(org.springframework.transaction.annotation.Transactional)")public void afterTransaction(JoinPoint joinPoint) {System.out.println("After transactional method: " + joinPoint.getSignature());}
}
以上是两种常用的切点表达式及其使用方法,你可以根据具体需求选择合适的方式来定义切点。希末对你有所帮助!如果有任何问题,欢迎继续提问。
3.5.2 @annotation
Spring AOP(面向切面编程)是 Spring 框架提供的一个重要特性,它通过代理机制实现了对方法的拦截和增强。结合自定义注解,我们可以实现更加灵活和精确的方法拦截,下面是实现自定义注解的全步骤以及一个简单的案例说明:
步骤一:定义自定义注解
首先,我们需要定义一个自定义注解,用于标记需要被拦截的方法。例如,我们定义一个 @LogExecutionTime
注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
@Target(ElementType.METHOD)
和 @Retention(RetentionPolicy.RUNTIME)
是 Java 中的注解(Annotation),用于对方法进行标记和描述。
-
@Target(ElementType.METHOD)
:- 参数:
ElementType.METHOD
表示该注解可以用于标记方法。 - 作用:指定了该注解可以使用的目标元素类型,这里是方法。这意味着这个注解只能用来修饰方法,不能用来修饰其他类型的元素,比如类、字段等。
- 参数:
-
@Retention(RetentionPolicy.RUNTIME)
:- 参数:
RetentionPolicy.RUNTIME
表示该注解在运行时可以通过反射获取到。 - 作用:指定了该注解的生命周期,即在什么时候注解信息会丢失。
RetentionPolicy.RUNTIME
表示这个注解会被保留到运行时,可以通过反射获取到这个注解的信息,从而在运行时进行相应的处理。
- 参数:
综合起来,@Target(ElementType.METHOD)
表示该注解只能用于标记方法,而 @Retention(RetentionPolicy.RUNTIME)
则表示这个注解的信息会被保留到运行时,可以在运行时通过反射获取到这个注解的信息。
步骤二:编写切面类
接下来,我们需要编写一个切面类,用于定义拦截逻辑。在这个切面类中,我们可以通过 @Around
注解来定义在方法执行前后需要执行的逻辑。
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;@Aspect
@Component
public class LogAspect {@Around("@annotation(LogExecutionTime)")public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {long startTime = System.currentTimeMillis();Object proceed = joinPoint.proceed();long executionTime = System.currentTimeMillis() - startTime;System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");return proceed;}
}
步骤三:配置 Spring AOP
在 Spring 配置文件中配置切面类的扫描和自动代理创建:
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.example"/>
案例说明
假设我们有一个服务类 UserService
,其中有一个方法 getUserById
需要记录执行时间:
import org.springframework.stereotype.Service;@Service
public class UserService {@LogExecutionTimepublic String getUserById(Long userId) {// 模拟业务逻辑return "User: " + userId;}
}
当调用 getUserById
方法时,由于标记了 @LogExecutionTime
注解,切面类 LogAspect
中的 logExecutionTime
方法会被触发,记录方法执行时间。
通过以上步骤,我们实现了借助 Spring AOP 原理实现自定义注解的全步骤,并且通过案例说明展示了如何使用自定义注解来实现方法拦截和增强。