spring @order注解

rder的规则:

order的值越小,优先级越高

order如果不标注数字,默认最低优先级,因为其默认值是int最大值

该注解等同于实现Ordered接口getOrder方法,并返回数字。

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
    int value() default 2147483647;
}

例子:

OrderRunner1.java

@Component
@Order(1)
public class OrderRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("The OrderRunner1 start to initialize ...");
    }
}

OrderRunner2.java

@Component
@Order(2)
public class OrderRunner2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("The OrderRunner2 start to initialize ...");
    }
}

启动日志:



The OrderRunner1 start to initialize …
The OrderRunner2 start to initialize …

Leave a Comment