SpringBoot之Order注解啟動順序


order的規則:

order的值越小,優先級越高
order如果不標注數字,默認最低優先級,因為其默認值是int最大值
該注解等同於實現Ordered接口getOrder方法,並返回數字。

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {

/**
* The order value.
* <p>Default is {@link Ordered#LOWEST_PRECEDENCE}.
* @see Ordered#getOrder()
*/
int value() default Ordered.LOWEST_PRECEDENCE;

}
 

int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
@Aspect
@Component
public class DataSourceAspect implements Ordered {

@Override
public int getOrder() {
return 1;
}

}
見下: 

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 ...");
}
}
 Runner.java

@Component
public class Runner implements CommandLineRunner {

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

public static void main(String[] args) {
System.out.println("The service to start.");
SpringApplication.run(CommandLineRunnerApplication.class, args);
System.out.println("The service has started.");
}
}
 

它們的啟動日志:

The service to start.
...
...
The OrderRunner1 start to initialize ...
The OrderRunner2 start to initialize ...
The Runner start to initialize ...
The service has started.
 
---------------------
作者:jiangxwa
來源:CSDN
原文:https://blog.csdn.net/jiangxwa/article/details/87892577
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM