springboot項目啟動成功後執行一段代碼的兩種方式
阿新 • • 發佈:2018-11-08
參數 註解 etime mman pac cycle net org 啟動
springboot項目啟動成功後執行一段代碼的兩種方式
實現ApplicationRunner接口
package com.lnjecit.lifecycle; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;/** * @author lnj * createTime 2018-11-07 22:37 **/ @Component public class ApplicationRunnerImpl implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("通過實現ApplicationRunner接口,在spring boot項目啟動後打印參數"); String[] sourceArgs= args.getSourceArgs(); for (String arg : sourceArgs) { System.out.print(arg + " "); } System.out.println(); } }
項目啟動後,會打印如下信息:
實現CommandLineRunner接口
package com.lnjecit.lifecycle; import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component; /** * @author lnj * createTime 2018-11-07 22:25 **/ @Component public class CommandLineRunnerImpl implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("通過實現CommandLineRunner接口,在spring boot項目啟動後打印參數"); for (String arg : args) { System.out.print(arg + " "); } System.out.println(); } }
兩種實現方式的不同之處在於run方法中接收的參數類型不一樣
指定執行順序
當項目中同時實現了ApplicationRunner和CommondLineRunner接口時,可使用Order註解或實現Ordered接口來指定執行順序,值越小越先執行
案例地址
https://github.com/linj6/springboot-learn/tree/master/springboot-runner
參考資料
https://blog.csdn.net/zknxx/article/details/52196427
springboot項目啟動成功後執行一段代碼的兩種方式