广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用SpringBoot的CommandLineRunner遇到的坑及解决
  • 225
分享到

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

使用SpringBootCommandLineRunner的坑SpringBootCommandLineRunner 2023-02-13 15:02:37 225人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录使用场景两个接口的不同特殊的场景遇到的坑填坑总结使用场景 再应用程序开发过程中,往往我们需要在容器启动的时候执行一些操作。 Spring Boot中提供了CommandLineR

使用场景

再应用程序开发过程中,往往我们需要在容器启动的时候执行一些操作。

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方法执行的是一个循环,循环到第四次的时候,抛出异常,直接影响主程序的启动。

填坑

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


@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,填坑成功。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: 使用SpringBoot的CommandLineRunner遇到的坑及解决

本文链接: https://www.lsjlt.com/news/195828.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用SpringBoot的CommandLineRunner遇到的坑及解决
    目录使用场景两个接口的不同特殊的场景遇到的坑填坑总结使用场景 再应用程序开发过程中,往往我们需要在容器启动的时候执行一些操作。 Spring Boot中提供了CommandLineR...
    99+
    2023-02-13
    使用SpringBoot CommandLineRunner的坑 SpringBoot CommandLineRunner
  • springboot连接sqllite遇到的坑及解决
    目录springboot连接sqllite的坑springboot集成sqlite配置设置springboot集成sqlitespringboot连接sqllite的坑 2021-0...
    99+
    2022-11-13
  • SpringBoot测试junit遇到的坑及解决
    目录一、NullPointerException原因解决二、org.springframework.context.ApplicationContextException三、java...
    99+
    2022-11-13
  • spring/springboot整合curator遇到的坑及解决
    目录整个代码可项目遇到了两个问题解决办法近期本人在搭建自己的调度平台项目使用到了zookeeper做执行器自动注册中心时,使用到了springboot2.0+curator4.0版本...
    99+
    2022-11-13
  • springcloudoauth2feign遇到的坑及解决
    目录springcloudoauth2feign遇到的坑客户端模式基于springsecurityspringcloud微服务增加oauth2权限后feign调用报null一般是这样...
    99+
    2022-11-13
  • @ConfigurationProperties遇到的坑及解决
    想着偷懒,直接使用@ConfigurationProperties(prefix="xxx")读取配置文件,不使用@Value("${xxx}")去一个一个的注入。 遇到的坑: 创...
    99+
    2022-11-12
  • vue使用mui遇到的坑及解决
    目录使用mui遇到的坑记录mui的js冲突了,有2种解决方法方法1方法2使用mui遇到的坑记录 主要用到webpack打包工具与mui,mint ui,其中mui有不少坑,在此记录 ...
    99+
    2022-11-13
  • 使用flutter的showModalBottomSheet遇到的坑及解决
    目录遇到了三个比较坑的地方我们解决完后的效果如下解决问题一解决问题二解决问题三在使用官方的showModalBottomSheet这个组件时到目前为止 遇到了三个比较坑的地方 1. ...
    99+
    2022-11-13
  • 解决SpringBoot整合RocketMQ遇到的坑
    应用场景 在实现RocketMQ消费时,一般会用到@RocketMQMessageListener注解定义Group、Topic以及selectorExpression(数...
    99+
    2022-11-12
  • 解决springboot整合druid遇到的坑
    springboot整合druid的坑 项目环境 springboot 2.1.6.RELEASE jdk 1.8 pom.xml配置 <?xm...
    99+
    2022-11-12
  • springboot访问静态资源遇到的坑及解决
    目录访问静态资源遇到的坑及解决直接访问静态资源的问题SpringBoot 默认静态资源访问配置引入shiro 或 security后的拦截过滤访问静态资源遇到的坑及解决 开始是以这...
    99+
    2022-11-13
  • 使用@Validated 和 BindingResult 遇到的坑及解决
    @Validated和BindingResult 使用遇到的坑 @Validated 与BindingResult 需要相邻,否则 变量result 不能接受错误信息 控制台输出 ...
    99+
    2022-11-12
  • SpringBoot遇到的坑@Qualifier报红的解决
    目录SpringBoot遇到的坑@Qualifier报红解决方法SpringBoot注解@Qualifier用法SpringBoot遇到的坑@Qualifier报红 今天写项目的时候...
    99+
    2022-11-12
  • 使用vue导出excel遇到的坑及解决
    目录vue导出excel遇到的坑需求准备工作vue导出excel表报错处理vue导出excel遇到的坑 需求 Vue+element UI el-table下的导出当前所有数据到一个...
    99+
    2022-11-13
  • vue+freemarker中遇到的坑及解决
    目录vue+freemarker遇到的坑在这个过程中遇到了几个坑freemarker的一些坑问题1.对空对象十分敏感2.freemarker中的${}与js中的${}冲突3.渲染数字...
    99+
    2022-11-13
  • 解决SpringBoot配置文件application.yml遇到的坑
    目录配置文件application.yml遇到的坑1.第一个坑,原代码解决办法2.第二个坑,原代码参见下图解决办法配置文件application.yml的注意事项这类似于还有一种配置...
    99+
    2022-11-13
  • SpringBoot整合RocketMQ遇到的坑怎么解决
    本篇内容主要讲解“SpringBoot整合RocketMQ遇到的坑怎么解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot整合RocketMQ遇到的坑怎么解决”吧!应用场景在实...
    99+
    2023-06-08
  • springboot连接sqllite遇到的坑如何解决
    本篇内容主要讲解“springboot连接sqllite遇到的坑如何解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“springboot连接sqllite遇到的坑如何解决”吧!springbo...
    99+
    2023-07-02
  • 解决使用openpyxl时遇到的坑
    最近在用python处理Excel表格是遇到了一些问题 1, xlwt最多只能写入65536行数据, 所以在处理大批量数据的时候没法使用 2, openpyxl 这个库, 在使用的时...
    99+
    2022-11-11
  • 解决SpringBoot使用yaml作为配置文件遇到的坑
    目录SpringBoot yaml作为配置文件遇到的坑背景感觉修改一下比较好,类似这样:SpringBoot-yaml配置注入yaml基础语法字面量:普通的值 [ 数字,布尔值,字符...
    99+
    2022-11-12
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作