天天看點

ApplicationRunner- 實作項目啟動就執行的功能

1.ApplicationRunner

是一個接口,常用于項目啟動後,(也就是ApringApplication.run()執行結束),立馬執行某些邏輯。

可用于項目的準備工作,比如加載配置檔案,加載執行流,定時任務等等。

2.如何使用ApplicationRunner

(可以有多個執行個體實作該接口,但是一般需要增加注解@Order來指定加載順序)

@Component
@Order(2)
public class JDDRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(args);
System.out.println("這個是測試ApplicationRunner接口");
}
}      

2.1.實作ApplicationRunner接口,重寫run方法,定義具體的執行邏輯

2.2.@Order注解,用于決定多個bean的執行順序,按照值從小到大執行 (值可為負數)

@Order(-1)優先于@Order(0)

@Order(1)優先于@Order(2)

3.還有個接口,也可以實作和ApplicationRunner一樣的功能

CommandLineRunner

CommandLineRunner接口的run方法接收的參數為String數組