日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

CommandLineRunner、ApplicationRunner 接口

發布時間:2024/9/30 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CommandLineRunner、ApplicationRunner 接口 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ?如果我們想在項目啟動后做一些事情(如加載定時任務,初始化工作),可以使用spring提供的CommandLineRunner、ApplicationRunner 接口,在容器啟動成功后的最后一步回調(類似開機自啟動)。

1. CommandLineRunner接口

/*** Interface used to indicate that a bean should <em>run</em> when it is contained within* a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined* within the same application context and can be ordered using the {@link Ordered}* interface or {@link Order @Order} annotation.* <p>* If you need access to {@link ApplicationArguments} instead of the raw String array* consider using {@link ApplicationRunner}.** @author Dave Syer* @see ApplicationRunner*/ public interface CommandLineRunner {/*** Callback used to run the bean.* @param args incoming main method arguments* @throws Exception on error*/void run(String... args) throws Exception;}

多個CommandLineRunner可以被同時執行在同一個spring上下文中并且執行順序是以order注解的參數順序一致。

下面看一個demo:

@Order(2) @Component public class ServerStartedReport implements CommandLineRunner{@Overridepublic void run(String... args) throws Exception {System.out.println("===========ServerStartedReport啟動====="+ LocalDateTime.now());} }

配置參數啟動項目:

控制臺打印:

[ddd,tyy] ===========ServerStartedReport啟動=====2019-02-14T21:31:30.466

2. ApplicationRunner接口

? ? ? ?二者基本一樣,區別在于接收的參數不一樣。CommandLineRunner的參數是最原始的參數,沒有做任何處理,而ApplicationRunner的參數是ApplicationArguments,對原始參數做了進一步的封裝。
如我們在這里配置了一些啟動參數--foo=hu --log=debug

CommandLineRunner只是獲取--name=value。而ApplicationRunner可以解析--name=value,使得我們可以直接通過name來獲取value。

import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component;import java.util.Arrays;@Component public class MyApplicationRunner implements ApplicationRunner{@Overridepublic void run(ApplicationArguments args) throws Exception {System.out.println("ApplicationRunner:"+ Arrays.asList(args.getSourceArgs()));System.out.println("getOptionNames:"+args.getOptionNames());System.out.println("getOptionValues:"+args.getOptionValues("foo"));System.out.println("getOptionValues:"+args.getOptionValues("log"));} }

打印結果為:

===========ServerStartedReport啟動=====2019-02-14T21:36:23.668 ApplicationRunner:[--foo=hu, --log=debug] getOptionNames:[log, foo] getOptionValues:[hu] getOptionValues:[debug]

注意啟動后執行的方法一定要加try catch,因為此處拋出異常會影響項目啟動。

總結

以上是生活随笔為你收集整理的CommandLineRunner、ApplicationRunner 接口的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。