使用SpringBoot的CommandLineRunner遇到的坑
點(diǎn)擊上方“程序員大白”,選擇“星標(biāo)”公眾號(hào)
重磅干貨,第一時(shí)間送達(dá)

來(lái)源:blog.csdn.net/zwq_zwq_zwq/article/details/81059017
使用場(chǎng)景
再應(yīng)用程序開(kāi)發(fā)過(guò)程中,往往我們需要在容器啟動(dòng)的時(shí)候執(zhí)行一些操作。Spring Boot中提供了CommandLineRunner和ApplicationRunner兩個(gè)接口來(lái)實(shí)現(xiàn)這樣的需求。
兩個(gè)接口的不同
參數(shù)不同,其他大體相同,可根據(jù)實(shí)際需求選擇合適的接口使用。CommandLineRunner接口中run方法的參數(shù)為String數(shù)組,ApplicationRunner中run方法的參數(shù)為ApplicationArguments。
特殊的場(chǎng)景
在啟動(dòng)項(xiàng)目時(shí),有時(shí)候我們所做的操作可能不是一次性的操作,有可能循環(huán)查詢數(shù)據(jù)庫(kù),根據(jù)結(jié)果來(lái)處理不同的業(yè)務(wù),亦或是監(jiān)聽(tīng)消息隊(duì)列……
遇到的坑
看下面一個(gè)例子,我們啟動(dòng)一個(gè)spring boot項(xiàng)目,正常啟動(dòng)情況下,項(xiàng)目啟動(dòng)后會(huì)打印啟動(dòng)時(shí)間。如下圖所示
2018-07-16 01:48:22.378 INFO 9164 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-07-16 01:48:22.386 INFO 9164 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-07-16 01:48:22.386 INFO 9164 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-07-16 01:48:22.396 INFO 9164 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-07-16 01:48:22.417 INFO 9164 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2018-07-16 01:48:22.546 INFO 9164 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
2018-07-16 01:48:22.555 INFO 9164 --- [ main] com.hello.word.WordParseApplication : Started WordParseApplication in 3.811 seconds (JVM running for 4.486)
下面我們模擬一下啟動(dòng)項(xiàng)目時(shí)使用CommandLineRunner,有人說(shuō)CommandLineRunner是項(xiàng)目啟動(dòng)完成后才調(diào)用的,我們看看現(xiàn)象。
@Component
public class RunService implements CommandLineRunner {
public void run(String... strings){
int i =0;
while(true){
i++;
try {
Thread.sleep(10000);
System.out.println("過(guò)去了10秒鐘……,i的值為:"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==4){ //第40秒時(shí)拋出一個(gè)異常
throw new RuntimeException();
}
continue;
}
}
}
再次啟動(dòng)spring boot 項(xiàng)目,看看日志,直接報(bào)錯(cuò),啟動(dòng)異常了。
2018-07-16 01:56:43.703 INFO 7424 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-07-16 01:56:43.703 INFO 7424 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-07-16 01:56:43.722 INFO 7424 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-07-16 01:56:43.750 INFO 7424 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2018-07-16 01:56:43.885 INFO 7424 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
過(guò)去了10秒鐘……,i的值為:1
過(guò)去了10秒鐘……,i的值為:2
過(guò)去了10秒鐘……,i的值為:3
過(guò)去了10秒鐘……,i的值為:4
2018-07-16 01:57:23.939 INFO 7424 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-07-16 01:57:23.973 ERROR 7424 --- [ main] o.s.boot.SpringApplication : Application startup failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at com.hello.word.WordParseApplication.main(WordParseApplication.java:15) [classes/:na]
Caused by: java.lang.RuntimeException: null
at com.zhangwq.service.RunService.run(RunService.java:24) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
... 6 common frames omitted
2018-07-16 01:57:23.975 INFO 7424 --- [ main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@14a4e18: startup date [Mon Jul 16 01:56:39 CST 2018]; root of context hierarchy
2018-07-16 01:57:23.975 INFO 7424 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 2147483647
2018-07-16 01:57:23.975 INFO 7424 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
Process finished with exit code 1
說(shuō)明啟動(dòng)CommandLineRunner的執(zhí)行其實(shí)是整個(gè)應(yīng)用啟動(dòng)的一部分,沒(méi)有打印最后的啟動(dòng)時(shí)間,說(shuō)明項(xiàng)目是在CommandLineRunner執(zhí)行完成之后才啟動(dòng)完成的。此時(shí)CommandLineRunner的run方法執(zhí)行的是一個(gè)循環(huán),循環(huán)到第四次的時(shí)候,拋出異常,直接影響主程序的啟動(dòng)。(搜索公眾號(hào)Java知音,回復(fù)“2021”,送你一份Java面試題寶典)
填坑
這樣的問(wèn)題該如何解決呢?這個(gè)操作影響了主線程,那么我們是否可以重新開(kāi)啟一個(gè)線程,讓他單獨(dú)去做我們想要做的操作呢。
@Component
public class RunService implements CommandLineRunner {
public void run(String... strings){
new Thread(){
public void run() {
int i = 0;
while (true) {
i++;
try {
Thread.sleep(10000);
System.out.println("過(guò)去了10秒鐘……,i的值為:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 4) { //第40秒時(shí)拋出一個(gè)異常
throw new RuntimeException();
}
continue;
}
}
}.start();
}
}
我們?cè)倏纯催@次的日志是什么樣的
2018-07-16 02:05:52.680 INFO 7148 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-07-16 02:05:52.680 INFO 7148 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-07-16 02:05:52.695 INFO 7148 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-07-16 02:05:52.717 INFO 7148 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2018-07-16 02:05:52.815 INFO 7148 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
2018-07-16 02:05:52.819 INFO 7148 --- [ main] com.hello.word.WordParseApplication : Started WordParseApplication in 3.406 seconds (JVM running for 4.063)
過(guò)去了10秒鐘……,i的值為:1
過(guò)去了10秒鐘……,i的值為:2
過(guò)去了10秒鐘……,i的值為:3
過(guò)去了10秒鐘……,i的值為:4
Exception in thread "Thread-10" java.lang.RuntimeException
at com.zhangwq.service.RunService$1.run(RunService.java:26)
此時(shí)CommandLineRunner執(zhí)行的操作和主線程是相互獨(dú)立的,拋出異常并不會(huì)影響到主線程。程序打印了啟動(dòng)時(shí)間,并且CommandLineRunner中run方法報(bào)錯(cuò)后,應(yīng)用程序并沒(méi)有因?yàn)楫惓6K止。填坑成功。
推薦閱讀
國(guó)產(chǎn)小眾瀏覽器因屏蔽視頻廣告,被索賠100萬(wàn)(后續(xù))
年輕人“不講武德”:因看黃片上癮,把網(wǎng)站和786名女主播起訴了
關(guān)于程序員大白
程序員大白是一群哈工大,東北大學(xué),西湖大學(xué)和上海交通大學(xué)的碩士博士運(yùn)營(yíng)維護(hù)的號(hào),大家樂(lè)于分享高質(zhì)量文章,喜歡總結(jié)知識(shí),歡迎關(guān)注[程序員大白],大家一起學(xué)習(xí)進(jìn)步!

