Java SpringBoot CommandLineRunner

使用场景

再应用程序开发过程中,往往需要在容器启动的时候执行一些操作。Spring Boot中提供了CommandLineRunnerApplicationRunner两个接口来实现这样的需求。

两个接口的不同

参数不同,其他大体相同,可根据实际需求选择合适的接口使用。CommandLineRunner接口中run方法的参数为String数组,ApplicationRunnerrun方法的参数为ApplicationArguments

特殊的场景

在启动项目时,有时候所做的操作可能不是一次性的操作,有可能循环查询数据库,根据结果来处理不同的业务,亦或是监听消息队列……

遇到的坑

看下面一个例子,启动一个spring boot项目,正常启动情况下,项目启动后会打印启动时间。如下图所示

  1. 2018-07-16 01:48:22.378 INFO 9164 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
  2. 2018-07-16 01:48:22.386 INFO 9164 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
  3. 2018-07-16 01:48:22.386 INFO 9164 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
  4. 2018-07-16 01:48:22.396 INFO 9164 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
  5. 2018-07-16 01:48:22.417 INFO 9164 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
  6. 2018-07-16 01:48:22.546 INFO 9164 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
  7. 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)

下面模拟一下启动项目时使用CommandLineRunner,有人说CommandLineRunner是项目启动完成后才调用的,看看现象。

  1. @Component
  2. public class RunService implements CommandLineRunner {
  3. public void run(String... strings){
  4. int i =0;
  5. while(true){
  6. i++;
  7. try {
  8. Thread.sleep(10000);
  9. System.out.println("过去了10秒钟……,i的值为:"+i);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. if(i==4){ //第40秒时抛出一个异常
  14. throw new RuntimeException();
  15. }
  16. continue;
  17. }
  18. }
  19. }

再次启动spring boot 项目,看看日志,直接报错,启动异常了。

  1. 2018-07-16 01:56:43.703 INFO 7424 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
  2. 2018-07-16 01:56:43.703 INFO 7424 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
  3. 2018-07-16 01:56:43.722 INFO 7424 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
  4. 2018-07-16 01:56:43.750 INFO 7424 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
  5. 2018-07-16 01:56:43.885 INFO 7424 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
  6. 过去了10秒钟……,i的值为:1
  7. 过去了10秒钟……,i的值为:2
  8. 过去了10秒钟……,i的值为:3
  9. 过去了10秒钟……,i的值为:4
  10. 2018-07-16 01:57:23.939 INFO 7424 --- [ main] utoConfigurationReportLoggingInitializer :
  11. Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
  12. 2018-07-16 01:57:23.973 ERROR 7424 --- [ main] o.s.boot.SpringApplication : Application startup failed
  13. java.lang.IllegalStateException: Failed to execute CommandLineRunner
  14. at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  15. at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  16. at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  17. at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  18. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  19. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  20. at com.hello.word.WordParseApplication.main(WordParseApplication.java:15) [classes/:na]
  21. Caused by: java.lang.RuntimeException: null
  22. at com.zhangwq.service.RunService.run(RunService.java:24) ~[classes/:na]
  23. at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
  24. ... 6 common frames omitted
  25. 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
  26. 2018-07-16 01:57:23.975 INFO 7424 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 2147483647
  27. 2018-07-16 01:57:23.975 INFO 7424 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
  28. Process finished with exit code 1

说明启动CommandLineRunner的执行其实是整个应用启动的一部分,没有打印最后的启动时间,说明项目是在CommandLineRunner执行完成之后才启动完成的。此时CommandLineRunnerrun方法执行的是一个循环,循环到第四次的时候,抛出异常,直接影响主程序的启动。

填坑

这样的问题该如何解决呢?这个操作影响了主线程,那么是否可以重新开启一个线程,让他单独去做想要做的操作呢。

  1. @Component
  2. public class RunService implements CommandLineRunner {
  3. public void run(String... strings){
  4. new Thread(){
  5. public void run() {
  6. int i = 0;
  7. while (true) {
  8. i++;
  9. try {
  10. Thread.sleep(10000);
  11. System.out.println("过去了10秒钟……,i的值为:" + i);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. if (i == 4) { //第40秒时抛出一个异常
  16. throw new RuntimeException();
  17. }
  18. continue;
  19. }
  20. }
  21. }.start();
  22. }
  23. }

再看看这次的日志是什么样的

  1. 2018-07-16 02:05:52.680 INFO 7148 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
  2. 2018-07-16 02:05:52.680 INFO 7148 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
  3. 2018-07-16 02:05:52.695 INFO 7148 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
  4. 2018-07-16 02:05:52.717 INFO 7148 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
  5. 2018-07-16 02:05:52.815 INFO 7148 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
  6. 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)
  7. 过去了10秒钟……,i的值为:1
  8. 过去了10秒钟……,i的值为:2
  9. 过去了10秒钟……,i的值为:3
  10. 过去了10秒钟……,i的值为:4
  11. Exception in thread "Thread-10" java.lang.RuntimeException
  12. at com.zhangwq.service.RunService$1.run(RunService.java:26)

此时CommandLineRunner执行的操作和主线程是相互独立的,抛出异常并不会影响到主线程。程序打印了启动时间,并且CommandLineRunnerrun方法报错后,应用程序并没有因为异常而终止。