Spring注解执行的默认顺序

对于同一个方法,上面加了n个注解,如下所示。

@AnnotationOne @AnnotationTwo public void test() { ……………………………… } 如果,不加order来强制表示顺序的话,这2个注解执行的默认顺序是什么样子的呢?

经查阅Spring官方文档https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-ataspectj-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 through 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 that you can order at the aspect level.

中文翻译如下:

当在同一Join Point上出现多个Advice时怎么办呢? Spring AOP遵循与AspectJ相同的优先级规则来确定建议执行的顺序。在进来时,优先级最高的Advice首先运行,在出去时,优先级最高的Advice最后运行。

当在不同aspect定义的两条Advice都需要在同一Join Point上运行时,除非专门指定顺序,否则它们的执行顺序是不确定的。您可以通过指定优先级来控制执行顺序,方法有两种:1. 在aspect类中实现org.springframework.core.Ordered接口,2. 使用Order注解。通常来说,Ordered.getValue()(或者注释值)返回较低值的aspect具有较高的优先级。

当在相同aspect定义的两条Advice都需要在同一Join Point上运行时,其执行顺序也是不确定的(因为通过对java已编译好的类进行反射操作,是无法获取声明顺序的)。要么,你可以考虑将这两条Advice合并成一个Advice,要么,可以将这两条Advice重构成两个aspect类,就能够使用Order来自定义顺序了。

posted @ 2022-01-17 13:59  八英里  阅读(743)  评论(0编辑  收藏  举报