springboot專案啟動成功後執行一段程式碼的兩種方式
阿新 • • 發佈:2018-11-07
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