1. 程式人生 > 其它 >Spring中的CommandLineRunner、ApplicationRunner 介面

Spring中的CommandLineRunner、ApplicationRunner 介面

CommandLineRunner、ApplicationRunner 介面是在容器啟動成功後的最後一步回撥(類似開機自啟動)。

CommandLineRunner介面

官方doc:

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or Order @Order annotation.
介面被用作將其加入spring容器中時執行其run方法。多個CommandLineRunner可以被同時執行在同一個spring上下文中並且執行順序是以order註解的引數順序一致。

If you need access to ApplicationArguments instead of the raw String array consider using ApplicationRunner.
如果你需要訪問ApplicationArguments去替換掉字串陣列,可以考慮使用ApplicationRunner類。

先看一個demo:
定義一個ServerStartedReport實現CommandLineRunner,並納入到srping容器中進行處理

 

 定義一個ServerSuccessReport實現CommandLineRunner,並納入到spring容器處理

 

啟動類測試,也可以直接在spring容器訪問該值:

配置引數,然後執行啟動類:

列印結果

 

 

ApplicationRunner介面

 

發現二者的官方javadoc一樣,區別在於接收的引數不一樣。CommandLineRunner的引數是最原始的引數,沒有做任何處理。ApplicationRunner的引數是ApplicationArguments,是對原始引數做了進一步的封裝。

ApplicationArguments是對引數(main方法)做了進一步的處理,可以解析--name=value的,我們就可以通過name來獲取value(而CommandLineRunner只是獲取--name=value)

 

 可以接收--foo=bar這樣的引數。

--getOptionNames()方法可以得到key的集合。
--getOptionValues(String name)方法可以得到key對應的value集合。

看一個demo:
定義DemoApplicationRunner類繼承ApplicationRunner介面:

 

配置引數啟動:

列印結果: