JAVA全系列 教程
3762个小节阅读:7090.7k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
因为AspectJ是编译增强,所以在使用AspectJ注解方式实现时,同一个切面中,相同类型通知的执行顺序和方法、类的编译顺序有关系。
主要分为三种情况:
强调:所说的相同类型通知肯定是同一个切面中,不是同一个切面的通知,没有套路的必要
同类中相同名称通知,按照名称确定执行顺序,下面代码先输出before1,后输出before2
xxxxxxxxxx
@Before("execution(* com.bjsxt.annotation.DemoServiceImpl.demo())")
public void before1(){
System.out.println("before1");
}
@Before("execution(* com.bjsxt.annotation.DemoServiceImpl.demo())")
public void before2(){
System.out.println("before2");
}
如果把before1方法名称变为before3,这时先输出before2,后输出before1
xxxxxxxxxx
@Before("execution(* com.bjsxt.annotation.DemoServiceImpl.demo())")
public void before3(){
System.out.println("before1");
}
@Before("execution(* com.bjsxt.annotation.DemoServiceImpl.demo())")
public void before2(){
System.out.println("before2");
}
不同类中相同类型通知的执行顺序和通知方法所在类的名称有关。不同类中通知和方法名称无关。
类名优先级高的通知 > 类名优先级低的 - 同类中优先级高的 > 类名优先级低的 - 同类中优先级高的。
也就是说:对于同类型通知类名优先级高的通知会全部执行完,才会执行类名优先级低的通知。
同类型通知包含:
新建AnnotationAdvice2类,并配置一个前置通知,发现输出顺序:环绕-前置->before2->before1->before3
xxxxxxxxxx
@Aspect
@Component
public class AnnotationAdvice2 {
@Before("execution(* com.bjsxt.annotation.DemoServiceImpl.demo())")
public void before1(){
System.out.println("before3");
}
}
修改AnnotationAdvice类名称为AnnotationAdvice3,执行发现执行顺序:
before3->环绕-前置->before2->before1
@Order注解可以控制通知类的优先级。参数value是int类型值,参数值越小优先级越高,一般多使用正数。
当使用@Order注解后,通知的执行顺序和类名无关。
注意:虽然@Order是类、方法、属性级注解。但是在Spring Framework 6中无法给同类相同类型通知控制执行顺序。
在AnnotationAdvice3中添加@Order,并设置参数为1
xxxxxxxxxx
@Aspect // 通知类必须有此注解
@Component
@Order(1)
public class AnnotationAdvice3 {
在AnnotationAdvice2中添加@Order,并设置参数为2
xxxxxxxxxx
@Aspect
@Component
@Order(2)
public class AnnotationAdvice2 {
运行程序,发现执行时执行顺序又变为:环绕-前置->before2->before1->before3