关于java:什么Spring-Boot-CommandLineRunner-有坑

应用场景

在利用程序开发过程中,往往咱们须要在容器启动的时候执行一些操作。

Spring Boot中提供了CommandLineRunner和ApplicationRunner两个接口来实现这样的需要。

两个接口的不同

参数不同,其余大体雷同,可依据理论需要抉择适合的接口应用。

CommandLineRunner接口中run办法的参数为String数组,ApplicationRunner中run办法的参数为ApplicationArguments。

非凡的场景

在启动我的项目时,有时候咱们所做的操作可能不是一次性的操作,有可能循环查询数据库,依据后果来解决不同的业务,亦或是监听音讯队列……

遇到的坑

看上面一个例子,咱们启动一个spring boot我的项目,失常启动状况下,我的项目启动后会打印启动工夫。如下图所示

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)

上面咱们模仿一下启动我的项目时应用CommandLineRunner,有人说CommandLineRunner是我的项目启动实现后才调用的,咱们看看景象。

@Component
public class RunService  implements CommandLineRunner {
 
    public void run(String... strings){
        int i =0;
        while(true){
            i++;
                try {
                    Thread.sleep(10000);
                    System.out.println("过来了10秒钟……,i的值为:"+i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(i==4){ //第40秒时抛出一个异样
                    throw new RuntimeException();
                }
                continue;
        }
    }
}

再次启动spring boot 我的项目,看看日志,间接报错,启动异样了。

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)
过来了10秒钟……,i的值为:1
过来了10秒钟……,i的值为:2
过来了10秒钟……,i的值为:3
过来了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

阐明启动CommandLineRunner的执行其实是整个利用启动的一部分,没有打印最初的启动工夫,阐明我的项目是在CommandLineRunner执行实现之后才启动实现的。

此时CommandLineRunner的run办法执行的是一个循环,循环到第四次的时候,抛出异样,间接影响主程序的启动。Spring Boot 教程和示例源码都在这里了:https://github.com/javastacks…

填坑

这样的问题该如何解决呢?

这个操作影响了主线程,那么咱们是否能够从新开启一个线程,让他独自去做咱们想要做的操作呢。

@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("过来了10秒钟……,i的值为:" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (i == 4) { //第40秒时抛出一个异样
                        throw new RuntimeException();
                    }
                    continue;
                }
            }
        }.start();
    }
}

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

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)
过来了10秒钟……,i的值为:1
过来了10秒钟……,i的值为:2
过来了10秒钟……,i的值为:3
过来了10秒钟……,i的值为:4
Exception in thread "Thread-10" java.lang.RuntimeException
 at com.zhangwq.service.RunService$1.run(RunService.java:26)

此时CommandLineRunner执行的操作和主线程是互相独立的,抛出异样并不会影响到主线程。

程序打印了启动工夫,并且CommandLineRunner中run办法报错后,应用程序并没有因为异样而终止。填坑胜利。

原文链接:https://blog.csdn.net/zwq_zwq…

版权申明:本文为CSDN博主「狮子头儿」的原创文章,遵循CC 4.0 BY-SA版权协定,转载请附上原文出处链接及本申明。

近期热文举荐:

1.600+ 道 Java面试题及答案整顿(2021最新版)

2.终于靠开源我的项目弄到 IntelliJ IDEA 激活码了,真香!

3.阿里 Mock 工具正式开源,干掉市面上所有 Mock 工具!

4.Spring Cloud 2020.0.0 正式公布,全新颠覆性版本!

5.《Java开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞+转发哦!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理