聊聊Spring AOP @Before @Around @After等advice的执行顺序
作者:rainbow702 发布时间:2022-10-27 18:14:20
用过spring框架进行开发的人,多多少少会使用过它的AOP功能,都知道有@Before、@Around和@After等advice。
最近,为了实现项目中的输出日志和权限控制这两个需求,我也使用到了AOP功能。
我使用到了@Before、@Around这两个advice。但在,使用过程中,却对它们的执行顺序并不清楚。
为了弄清楚在不同情况下,这些advice到底是以怎么样的一个顺序进行执行的,我作了个测试,在此将其记录下来,以供以后查看。
前提
对于AOP相关类(aspect、pointcut等)的概念,本文不作说明。
对于如何让spring框架扫描到AOP,本文也不作说明。
情况一: 一个方法只被一个Aspect类拦截
当一个方法只被一个Aspect拦截时,这个Aspect中的不同advice是按照怎样的顺序进行执行的呢?请看:
添加 PointCut类
该pointcut用来拦截test包下的所有类中的所有方法。
package test;
import org.aspectj.lang.annotation.Pointcut;
public class PointCuts {
@Pointcut(value = "within(test.*)")
public void aopDemo() {
}
}
添加Aspect类
该类中的advice将会用到上面的pointcut,使用方法请看各个advice的value属性。
package test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Aspect1 {
@Before(value = "test.PointCuts.aopDemo()")
public void before(JoinPoint joinPoint) {
System.out.println("[Aspect1] before advise");
}
@Around(value = "test.PointCuts.aopDemo()")
public void around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("[Aspect1] around advise 1");
pjp.proceed();
System.out.println("[Aspect1] around advise2");
}
@AfterReturning(value = "test.PointCuts.aopDemo()")
public void afterReturning(JoinPoint joinPoint) {
System.out.println("[Aspect1] afterReturning advise");
}
@AfterThrowing(value = "test.PointCuts.aopDemo()")
public void afterThrowing(JoinPoint joinPoint) {
System.out.println("[Aspect1] afterThrowing advise");
}
@After(value = "test.PointCuts.aopDemo()")
public void after(JoinPoint joinPoint) {
System.out.println("[Aspect1] after advise");
}
}
添加测试用Controller
添加一个用于测试的controller,这个controller中只有一个方法,但是它会根据参数值的不同,会作出不同的处理:一种是正常返回一个对象,一种是抛出异常(因为我们要测试@AfterThrowing这个advice)
package test;
import test.exception.TestException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/aop")
public class AopTestController {
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Result test(@RequestParam boolean throwException) {
// case 1
if (throwException) {
System.out.println("throw an exception");
throw new TestException("mock a server exception");
}
// case 2
System.out.println("test OK");
return new Result() {{
this.setId(111);
this.setName("mock a Result");
}};
}
public static class Result {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
测试 正常情况
在浏览器直接输入以下的URL,回车:
http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=false
我们会看到输出的结果是:
[Aspect1] around advise 1
[Aspect1] before advise
test OK
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise
测试 异常情况
在浏览器中直接输入以下的URL,回车:
http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=true
我们会看到输出的结果是:
[Aspect1] around advise 1
[Aspect1] before advise
throw an exception
[Aspect1] after advise
[Aspect1] afterThrowing advise
结论
在一个方法只被一个aspect类拦截时,aspect类内部的 advice 将按照以下的顺序进行执行:
正常情况:
异常情况:
情况二: 同一个方法被多个Aspect类拦截
此处举例为被两个aspect类拦截。
有些情况下,对于两个不同的aspect类,不管它们的advice使用的是同一个pointcut,还是不同的pointcut,都有可能导致同一个方法被多个aspect类拦截。那么,在这种情况下,这多个Aspect类中的advice又是按照怎样的顺序进行执行的呢?请看:
pointcut类保持不变
添加一个新的aspect类
package test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Aspect2 {
@Before(value = "test.PointCuts.aopDemo()")
public void before(JoinPoint joinPoint) {
System.out.println("[Aspect2] before advise");
}
@Around(value = "test.PointCuts.aopDemo()")
public void around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("[Aspect2] around advise 1");
pjp.proceed();
System.out.println("[Aspect2] around advise2");
}
@AfterReturning(value = "test.PointCuts.aopDemo()")
public void afterReturning(JoinPoint joinPoint) {
System.out.println("[Aspect2] afterReturning advise");
}
@AfterThrowing(value = "test.PointCuts.aopDemo()")
public void afterThrowing(JoinPoint joinPoint) {
System.out.println("[Aspect2] afterThrowing advise");
}
@After(value = "test.PointCuts.aopDemo()")
public void after(JoinPoint joinPoint) {
System.out.println("[Aspect2] after advise");
}
}
测试用Controller也不变
还是使用上面的那个Controller。但是现在 aspect1 和 aspect2 都会拦截该controller中的方法。
下面继续进行测试!
测试 正常情况
在浏览器直接输入以下的URL,回车:
http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=false
我们会看到输出的结果是:
[Aspect2] around advise 1
[Aspect2] before advise
[Aspect1] around advise 1
[Aspect1] before advise
test OK
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise
[Aspect2] around advise2
[Aspect2] after advise
[Aspect2] afterReturning advise
但是这个时候,我不能下定论说 aspect2 肯定就比 aspect1 先执行。
不信?你把服务务器重新启动一下,再试试,说不定你就会看到如下的执行结果:
[Aspect1] around advise 1
[Aspect1] before advise
[Aspect2] around advise 1
[Aspect2] before advise
test OK
[Aspect2] around advise2
[Aspect2] after advise
[Aspect2] afterReturning advise
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise
也就是说,这种情况下, aspect1 和 aspect2 的执行顺序是未知的。那怎么解决呢?不急,下面会给出解决方案。
测试 异常情况
在浏览器中直接输入以下的URL,回车:
http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=true
我们会看到输出的结果是:
[Aspect2] around advise 1
[Aspect2] before advise
[Aspect1] around advise 1
[Aspect1] before advise
throw an exception
[Aspect1] after advise
[Aspect1] afterThrowing advise
[Aspect2] after advise
[Aspect2] afterThrowing advise
同样地,如果把服务器重启,然后再测试的话,就可能会看到如下的结果:
[Aspect1] around advise 1
[Aspect1] before advise
[Aspect2] around advise 1
[Aspect2] before advise
throw an exception
[Aspect2] after advise
[Aspect2] afterThrowing advise
[Aspect1] after advise
[Aspect1] afterThrowing advise
也就是说,同样地,异常情况下, aspect1 和 aspect2 的执行顺序也是未定的。
那么在 情况二 下,如何指定每个 aspect 的执行顺序呢?
方法有两种:
实现org.springframework.core.Ordered接口,实现它的getOrder()方法
给aspect添加@Order注解,该注解全称为:org.springframework.core.annotation.Order
不管采用上面的哪种方法,都是值越小的 aspect 越先执行。
比如,我们为 apsect1 和 aspect2 分别添加 @Order 注解,如下:
@Order(5)
@Component
@Aspect
public class Aspect1 {
// ...
}
@Order(6)
@Component
@Aspect
public class Aspect2 {
// ...
}
这样修改之后,可保证不管在任何情况下, aspect1 中的 advice 总是比 aspect2 中的 advice 先执行。
如下图所示:
注意点
如果在同一个 aspect 类中,针对同一个 pointcut,定义了两个相同的 advice(比如,定义了两个 @Before),那么这两个 advice 的执行顺序是无法确定的,哪怕你给这两个 advice 添加了 @Order 这个注解,也不行。这点切记。
对于@Around这个advice,不管它有没有返回值,但是必须要方法内部,调用一下 pjp.proceed();否则,Controller 中的接口将没有机会被执行,从而也导致了 @Before这个advice不会被触发。
比如,我们假设正常情况下,执行顺序为”aspect2 -> apsect1 -> controller”,如果,我们把 aspect1中的@Around中的 pjp.proceed();给删掉,那么,我们看到的输出结果将是:
[Aspect2] around advise 1
[Aspect2] before advise
[Aspect1] around advise 1
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise
[Aspect2] around advise2
[Aspect2] after advise
[Aspect2] afterReturning advise
从结果可以发现, Controller 中的 接口 未被执行,aspect1 中的 @Before advice 也未被执行。
参考资料
Spring 4.3.2.RELEASE 官方资料:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/
其中,AOP的执行顺序章节为:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#aop-ataspectj-advice-ordering
Advice ordering
What happens when multiple pieces of advice all want to run at the same join point?
Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution.
The highest precedence advice runs first "on the way in" (so given two pieces of before advice, the one with highest precedence runs first).
"On the way out" from a join point, the highest precedence advice runs last (so given two pieces of after advice, the one with the highest precedence will run second).
When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise the order of execution is undefined.
You can control the order of execution by specifying precedence.
This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation.
Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.
When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined (since there is no way to retrieve the declaration order via reflection for javac-compiled classes).
Consider collapsing such advice methods into one advice method per join point in each aspect class, or refactor the pieces of advice into separate aspect classes - which can be ordered at the aspect level.
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/rainbow702/article/details/52185827


猜你喜欢
- kafka作为一个使用广泛的消息队列,很多人都不会陌生,但当你在网上搜索“kafka 延迟队列”,出
- JVM 的主要作用是什么?JVM 就是 Java Virtual Machine(Java虚拟机)的缩写,JVM 屏蔽了与具体操作系统平台相
- using System;using System.Data;using System.Data.OleDb;namespace ZFSof
- 什么是局部类型?C# 2.0 引入了局部类型的概念。局部类型允许我们将一个类、结构或接口分成几个部分,分别实现在几个不同的.cs文件中。局部
- 一、简介JetCache是一个基于Java的缓存系统封装,提供统一的API和注解来简化缓存的使用。 JetCache提供了比SpringCa
- 为什么需要在应用程序中增加渠道信息?Android应用的发布需要面对各种各样的市场,我们称之为渠道。有的时候,我们需要知道应用是从哪个渠道下
- 在X86的环境下,var wParam = (int)msg.WParam;工作得很好。在X64的环境下,快速滚动滚轮会出现msg.WPar
- 我们在使用editText控件的时候,会遇到这样的一问题,就是我在输入时候,当我选择让文字变粗时,我输入的文字就会变粗,当我去掉选择时,再输
- 1. java.lang.nullpointerexception 这个异常大家肯定都经常遇到,异常的解释是"程序遇上
- 在学习安卓的最初过程中我们学的都是最基本的一个活动,只有一个活动的应用也太简单了吧,没错我们的最求应该更高点,不管你创建多少个活动,接下里我
- 一个类,有时候搞不清楚到底用成员变量还是属性。 如: 成员变量 public string
- 为开发团队选择一款优秀的MVC框架是件难事儿,在众多可行的方案中决择需要很高的经验和水平。你的一个决定会影响团队未来的几年。要考虑方面太多:
- 1、 题外话 相信大家对LayoutInflate都不陌生,特别在ListView的Adapter的getV
- android 点击EditText始终不弹出软件键盘场景描述:正常情况下,当点击EditText时,软键盘会弹出来。现在的要求
- 1.狂妄的WPF相对传统的Windows图形编程,需要做很多复杂的工作,引用许多不同的API。例如:WinForm(带控件表单)、GDI+(
- 一:简述如果我们想要生成一个随机数,通常会使用Random类。但是在并 * 况下Random生成随机数的性能并不是很理想,今天给大家介绍一下J
- 1.点击上传按钮进行如下操作,通过表单名称以及input名称获取相应的值,对于上传的文件,使用.files来获取,因为包含文件的上传,所以采
- springboot+mybatis报错找不到实体类找不到实体类的错误可能有很多,接下来列举几个地方启动类位置不对,启动类应该在你的serv
- 上一篇JavaMail入门第四篇 接收邮件中,控制台打印出的内容,我们无法阅读,其实,让我们自己来解析一封复杂的邮件是很不容易的,邮件里面格
- DataBindings属性是很多控件都有的属性,作用有2方面。一方面是用于与数据库的数据进行绑定,进行数据显示。另一方面用于与控件或类的对