springboot 系統啟動時執行


有一些特殊的任務需要在系統啟動時執行,例如配置文件加載、數據庫初始化等操作。如果沒有使用Spring Boot,這些問題可以在Listener中解決。Spring Boot對此提供了兩種解決方案:CommandLineRunner和ApplicationRunner。CommandLineRunner和ApplicationRunner基本一致,差別主要體現在參數上。

 

CommandLineRunner

Spring Boot項目在啟動時會遍歷所有CommandLineRunner的實現類並調用其中的run方法,如果整個系統中有多個CommandLineRunner的實現類,那么可以使用@Order注解對這些實現類的調用順序進行排序。

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

    @Override
    public void run(String... args) {
        System.out.println("Runner1>>>" + Arrays.toString(args));
    }

}

• @Order(1)注解用來描述CommandLineRunner的執行順序,數字越小越先執行。

• run方法中是調用的核心邏輯,參數是系統啟動時傳入的參數,即入口類中main方法的參數(在調用SpringApplication.run方法時被傳入Spring Boot項目中)。 

 

ApplicationRunner

ApplicationRunner的用法和CommandLineRunner基本一致,區別主要體現在run方法的參數上。

@Component
@Order(1)
public class MyApplicationRunner1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) {
        List<String> nonOptionArgs = args.getNonOptionArgs();
        System.out.println("1-nonOptionArgs>>>" + nonOptionArgs);
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            System.out.println("1-key:" + optionName + ";value:" + args.getOptionValues(optionName));
        }
    }
}

• @Order注解依然是用來描述執行順序的,數字越小越優先執行。

• 不同於CommandLineRunner中run方法的String數組參數,這里run方法的參數是一個ApplicationArguments對象,如果想從ApplicationArguments對象中獲取入口類中main方法接收的參數,調用ApplicationArguments中的getNonOptionArgs方法即可。ApplicationArguments中的getOptionNames方法用來獲取項目啟動命令行中參數的key,例如將本項目打成jar包,運行java -jar xxx.jar –name=xc命令來啟動項目,此時getOptionNames方法獲取到的就是name,而getOptionValues方法則是獲取相應的value。

 

 

測試

jar啟動

java -jar xc-springboot-0.0.2-SNAPSHOT.jar --name=xc --age=18 a1 a2
• --name=xc --age=18都屬於getOptionNames/getOptionValues范疇。
• 后面的 a1 a2 可以通過getNonOptionArgs方法獲取,獲取到的是一個數組,相當於上文提到的運行時配置的ProgramArguments。
 

idea啟動

 結果:

 

 

參考文章: Spring Boot+Vue全棧開發實戰 - 4.9 啟動系統任務


免責聲明!

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



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