使用SpringBoot的CommandLineRunner遇到的坑及解决

 更新时间:2023年02月13日 14:04:53   作者:狮子头儿  
这篇文章主要介绍了使用SpringBoot的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是项目启动完成后才调用的,我们看看现象。

/**
 * @author zhangwq
 * @date 2018/7/16 1:36
 */
@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方法执行的是一个循环,循环到第四次的时候,抛出异常,直接影响主程序的启动。

填坑

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

/**
 * @author zhangwq
 * @date 2018/7/16 1:36
 */
@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方法报错后,应用程序并没有因为异常而终止。

ok,填坑成功。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringData如何通过@Query注解支持JPA语句和原生SQL语句

    SpringData如何通过@Query注解支持JPA语句和原生SQL语句

    这篇文章主要介绍了SpringData如何通过@Query注解支持JPA语句和原生SQL语句,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • java.io.UncheckedIOException: Cannot delete C:\Users\guo\AppData\Local\Temp\tomcat.8081问题

    java.io.UncheckedIOException: Cannot delete C

    本文主要介绍了java.io.UncheckedIOException: Cannot delete C:\Users\guo\AppData\Local\Temp\tomcat.8081问题,具有一定的参考价值,感兴趣的可以了解一下
    2024-05-05
  • mybatis 延迟加载的深入理解

    mybatis 延迟加载的深入理解

    这篇文章主要介绍了mybatis 延迟加载的深入理解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • java基于jdbc连接mysql数据库功能实例详解

    java基于jdbc连接mysql数据库功能实例详解

    这篇文章主要介绍了java基于jdbc连接mysql数据库功能,结合实例形式详细分析了jdbc连接mysql数据库的原理、步骤、实现方法及相关操作技巧,需要的朋友可以参考下
    2017-10-10
  • Jax-rs规范下REST接口使用方法详解

    Jax-rs规范下REST接口使用方法详解

    这篇文章主要介绍了Jax-rs规范下REST接口使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • Java中的HashMap和ConcurrentHashMap区别和适用场景

    Java中的HashMap和ConcurrentHashMap区别和适用场景

    HashMap和ConcurrentHashMap在对null值的处理、线程安全性、性能等方面存在显著的区别,HashMap允许键和值为null,适用于单线程环境下的数据存储和查询场景;而ConcurrentHashMap不允许键和值为null,适用多线程环境下的数据存储和查询场景,具有线程安全性和较高的并发性能
    2025-01-01
  • 深入了解Java GC的工作原理

    深入了解Java GC的工作原理

    下面小编就为大家带来一篇深入了解Java GC的工作原理。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • Maven项目读取resources文件路径问题解决方案

    Maven项目读取resources文件路径问题解决方案

    这篇文章主要介绍了Maven项目读取resources文件路径问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • java编程实现获取服务器IP地址及MAC地址的方法

    java编程实现获取服务器IP地址及MAC地址的方法

    这篇文章主要介绍了java编程实现获取机器IP地址及MAC地址的方法,实例分析了Java分别针对单网卡及多网卡的情况下获取服务器IP地址与MAC地址的相关技巧,需要的朋友可以参考下
    2015-11-11
  • java中的类型自动转换机制解析

    java中的类型自动转换机制解析

    这篇文章主要介绍了java中的类型自动转换机制,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03

最新评论