应用启动数据初始化接口CommandLineRunner和Application详解

 更新时间:2021年12月21日 14:41:40   作者:晴空排云  
这篇文章主要介绍了应用启动数据初始化接口CommandLineRunner和Application详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

应用启动数据初始化接口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 {
 }
}

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

相关文章

  • 分析ThreadLocal内存泄漏问题

    分析ThreadLocal内存泄漏问题

    ThreadLocal的作用是提供线程内的局部变量,这种变量在线程生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量传递的复杂度,但是如果滥用ThreadLocal可能会导致内存泄漏,所以本文将为大家分析ThreadLocal内存泄漏问题
    2023-07-07
  • java如何获取指定文件夹下的所有文件名

    java如何获取指定文件夹下的所有文件名

    这篇文章主要介绍了java如何获取指定文件夹下的所有文件名问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • Java接口和抽象类实例分析

    Java接口和抽象类实例分析

    这篇文章主要介绍了Java接口和抽象类,实例分析了java接口与抽象类的概念与相关使用技巧,需要的朋友可以参考下
    2015-05-05
  • 使用MyBatis快速生成代码的几种方法

    使用MyBatis快速生成代码的几种方法

    本文主要介绍了如何使用MyBatis快速生成代码的几种方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2023-12-12
  • java 判断字符串中是否有重复字符的示例

    java 判断字符串中是否有重复字符的示例

    今天小编就为大家分享一篇java 判断字符串中是否有重复字符的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • 详解SpringBoot静态方法获取bean的三种方式

    详解SpringBoot静态方法获取bean的三种方式

    本文主要介绍了详解SpringBoot静态方法获取bean的三种方式,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • Java中的运算符你知道多少

    Java中的运算符你知道多少

    这篇文章主要为大家详细介绍了Java中的运算符,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • tio-boot整合hotswap-classloader实现热加载方法实例

    tio-boot整合hotswap-classloader实现热加载方法实例

    这篇文章主要为大家介绍了tio-boot整合hotswap-classloader实现热加载方法实例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Java使用Lambda表达式查找list集合中是否包含某值问题

    Java使用Lambda表达式查找list集合中是否包含某值问题

    Java使用Lambda表达式查找list集合中是否包含某值的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • 基于java构造方法Vector修改元素源码分析

    基于java构造方法Vector修改元素源码分析

    本篇文章是关于ava构造方法Vector源码分析系列文章,本文主要介绍了Vector修改元素的源码分析,有需要的朋友可以借鉴参考下,希望可以有所帮助
    2021-09-09

最新评论