如何确保java中的注释执行顺序?

use*_*448 9 java spring annotations

我有2个自定义注释,但一个应始终在另一个之前执行.我如何确保这一点?是否有某种排序或使用其他方法定义?

Rom*_*man 5

您可以使用@Order批注来确保自定义批注的顺序。

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/Order.html

例:

第一个注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
}

@Aspect
@Component
@Order(value = 1)
public class CustomAnnotationInterceptor {

    @Before("@annotation(customAnnotation )")
    public void intercept(JoinPoint method, CustomAnnotation customAnnotation ) {
        //Code here
    }
}
Run Code Online (Sandbox Code Playgroud)

第二注:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotationTwo {
}

@Aspect
@Component
@Order(value = 2)
public class CustomAnnotationInterceptorTwo {

    @Before("@annotation(customAnnotationTwo )")
    public void intercept(JoinPoint method, CustomAnnotationTwo customAnnotationTwo ) {
        //Code here
    }
Run Code Online (Sandbox Code Playgroud)

使用它们:

@CustomAnnotationTwo
@CustomAnnotation
public void someMethod(){
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,CustomAnnotationInterceptor将首先执行。


小智 -1

是的,我认为注释本身提供了注释,例如@First和@Second等,所以你可以尝试一下

  • 你是这么认为还是你检查过?:) (6认同)