应用启动数据初始化接口CommandLineRunner和Application详解
作者:晴空排云 发布时间:2023-02-06 05:00:33
应用启动数据初始化接口CommandLineRunner和Application详解
在SpringBoot项目中创建组件类实现CommandLineRunner或ApplicationRunner接口可实现在应用启动之后及时进行一些初始化操作,如缓存预热、索引重建等等类似一些数据初始化操作。
两个接口功能相同,都有个run方法需要重写,只是实现方法的参数不同。
CommandLineRunner接收原始的命令行启动参数,ApplicationRunner则将启动参数对象化。
1 运行时机
两个接口都是在SpringBoot应用初始化好上下文之后运行,所以在运行过程中,可以使用上下文中的所有信息,例如一些Bean等等。在框架SpringApplication类源码的run方法中,可查看Runner的调用时机callRunners,如下:
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
//调用Runner,执行初始化操作
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
2 实现接口
2.1 CommandLineRunner
简单实现如下,打印启动参数信息:
@Order(1)
@Component
public class CommandLineRunnerInit implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private final String LOG_PREFIX = ">>>>>>>>>>CommandLineRunner >>>>>>>>>> ";
@Override
public void run(String... args) throws Exception {
try {
this.logger.error("{} args:{}", LOG_PREFIX, StringUtils.join(args, ","));
} catch (Exception e) {
logger.error("CommandLineRunnerInit run failed", e);
}
}
}
2.2 ApplicationRunner
简单实现如下,打印启动参数信息,并调用Bean的方法(查询用户数量):
@Order(2)
@Component
public class ApplicationRunnerInit implements ApplicationRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private final String LOG_PREFIX = ">>>>>>>>>>ApplicationRunner >>>>>>>>>> ";
private final UserRepository userRepository;
public ApplicationRunnerInit(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void run(ApplicationArguments args) throws Exception {
try {
this.logger.error("{} args:{}", LOG_PREFIX, JSONObject.toJSONString(args));
for (String optionName : args.getOptionNames()) {
this.logger.error("{} argName:{} argValue:{}", LOG_PREFIX, optionName, args.getOptionValues(optionName));
}
this.logger.error("{} user count:{}", LOG_PREFIX, this.userRepository.count());
} catch (Exception e) {
logger.error("CommandLineRunnerInit run failed", e);
}
}
}
3 执行顺序
如果实现了多个Runner,默认会按照添加顺序先执行ApplicationRunner的实现再执行CommandLineRunner的实现,如果多个Runner之间的初始化逻辑有先后顺序,可在实现类添加@Order注解设置执行顺序,可在源码SpringApplication类的callRunners方法中查看,如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
//先添加的ApplicationRunner实现
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
//再添加的CommandLineRunner实现
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
//如果设置了顺序,则按设定顺序重新排序
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
4 设置启动参数
为了便于对比效果,在Idea中设置启动参数如下图(生产环境中会自动读取命令行启动参数):
5 运行效果
在上面的两个Runner中,设定了CommandLineRunnerInit是第一个,ApplicationRunnerInit是第二个。启动应用,运行效果如下图:
ApplicationRunner和CommandLineRunner用法区别
业务场景:
应用服务启动时,加载一些数据和执行一些应用的初始化动作。如:删除临时文件,清除缓存信息,读取配置文件信息,数据库连接等。
1、SpringBoot提供了CommandLineRunner和ApplicationRunner接口。当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。
注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。
两者的区别在于:
ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口
ApplicationRunner
@Component
@Order(value = 10)
public class AgentApplicationRun2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
}
}
CommandLineRunner
@Component
@Order(value = 11)
public class AgentApplicationRun implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
}
}
来源:https://blog.csdn.net/lxh_worldpeace/article/details/105854497


猜你喜欢
- 概述对List进行分组是日常开发中,经常遇到的,在JDK 8中对List按照某个属性分组的代码,超级简单。package test;impo
- 思路不清晰的小伙伴可以先在es中把聚合代码写出来{ "aggs": { "
- 当屏幕变为横屏的时候,系统会重新呼叫当前Activity的OnCreate方法,你可以把以下方法放在你的OnCreate中来检查当前的方向,
- 目前较常用的分页实现办法有两种:1.每次翻页都修改SQL,向SQL传入相关参数去数据库实时查出该页的数据并显示。2.查出数据库某张表的全部数
- 现在很多app的支付、输入密码功能,都已经开始使用自定义数字键盘,不仅更加方便、其效果着实精致。下面带着大家学习下,如何 * 微信的数字键盘,
- Android 滑动返回Activity的实现代码近来玩微信的时候偶然发现,向左滑动朋友圈竟然可以返回主页,故引起兴趣特研究代码很简洁pac
- java 中cookie的详解Java对cookie的操作比较简单,主要介绍下建立cookie和读取cookie,以及如何设定cookie的
- 这是 Java 爬虫系列博文的第四篇,在上一篇Java 爬虫数据异步加载如何解决,试试这两种办法! 中,我们从内置浏览器内核和反向解析法两个
- 官方 JSON.NET 地址 http://james.newtonking.com/pages/json-net.aspxXML TO J
- 最近接了一个项目其中有功能要实现一个清理内存,要求和微信的效果一样。于是想到用surfaceView而不是继承view。下面小编给大家解析下
- 本文实例为大家分享了Spring MVC多文件上传的具体代码,供大家参考,具体内容如下1)创建工程并导入JAR包2)创建多文件选择页面在 W
- 本文实例讲述了Java实现数组转字符串及字符串转数组的方法。分享给大家供大家参考,具体如下:字符串转数组使用Java split() 方法s
- 一、概念 java对象序列化的意思就是将对象的状态转化成字节流,以后
- 本文实例讲述了Android Service中使用Toast无法正常显示问题的解决方法。分享给大家供大家参考,具体如下:在做Service简
- 1.统计字符串字母个数(并且保持字母顺序)比如: aabbbbbbbba喔喔bcab cdabc deaaa目前我做知道的有5种方式噢,如果
- web采集的数据为 %u6B63%u5F0F%u4EBA%u5458,需要读取并转换为python对象,想了下不调用Javascript去e
- Maven搭建springboot项目本文是基于Windows 10系统环境,使用Maven搭建springboot项目Windows 10
- 这篇文章主要介绍了简单了解java标识符的作用和命名规则,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 在app中图片的轮播显示可以说是非常常见的实现效果了,其实现原理不过是利用ViewPager,然后利用handler每隔一定的时间将View
- 本文参考借鉴:https://www.jb51.net/article/102983.htm先上效果图:自定义控件:AttendancePr