SpringBoot2.x基础篇:使用CommandLineRunner或ApplicationRunner

简介: 如果你想要使用`SpringBoot`构建的项目在启动后运行一些特定的代码,那么`CommandLineRunner`、`ApplicationRunner`都是很好的选择。

如果你想要使用SpringBoot构建的项目在启动后运行一些特定的代码,那么CommandLineRunnerApplicationRunner都是很好的选择。

推荐阅读

使用方式

我们以CommandLineRunner创建了一个简单的例子,如下所示:

/**
 * {@link CommandLineRunner}接口使用示例
 *
 * @author 恒宇少年
 */
@Component
public class CommandLineRunnerExample implements CommandLineRunner {
    /**
     * 实例化本类的日志采集器
     */
    static LoggingCollector logging = LoggingCollectorFactory.getCollector(CommandLineRunnerExample.class);

    @Override
    public void run(String... args) throws Exception {
        // 执行特定的代码
        logging.debug("main方法参数列表:{}", args);
    }
}

CommandLineRunner接口的定义很简单,只提供了一个名为#run()的方法,我们只需要实现该方法做一些自定义的业务逻辑即可,ApplicationRunner接口的使用方式也是一样的。

两者的区别?

从源码上分析,CommandLineRunnerApplicationRunner两者之间只有#run()方法的参数不一样而已。

CommandLineRunner:

@FunctionalInterface
public interface CommandLineRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    void run(String... args) throws Exception;

}

ApplicationRunner:

@FunctionalInterface
public interface ApplicationRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming application arguments
     * @throws Exception on error
     */
    void run(ApplicationArguments args) throws Exception;

}

CommandLineRunner#run()方法的参数是启动SpringBoot应用程序main方法的参数列表,而ApplicationRunner#run()方法的参数则是ApplicationArguments对象。

在之前的文章中也提到过ApplicatgionArguments对象,并使用它获取外部的配置参数,查看:应用程序在启动时访问启动项参数

建议:如果你在项目启动时需要获取类似 "--xxx" 的启动参数值建议使用 ApplicationRunner

什么时候会被调用?

我们已经了解CommandLineRunnerApplicationRunner两个接口的使用以及区别,是不是很想知道SpringBoot在启动时在什么时候调用它们的呢?

我们大家都知道SpringBoot应用程序的启动主要归功于SpringApplication这个类,我们在创建项目时在启动类内会调用SpringApplication#run()方法,如下所示:

public static void main(String[] args) {
  SpringApplication.run(LoggingServiceApplication.class, args);
}

那我们来查看下SpringApplication#run()方法的源码,根据查看方法之间的相互调用,最终我们会定位到org.springframework.boot.SpringApplication#run(java.lang.String...)这个方法,阅读该方法时发现有关调用Runner的定义,如下所示:

// 省略部分源码
listeners.started(context);
callRunners(context, applicationArguments);
// 省略部分源码

#callRunnners()方法的调用确实是在应用程序启动完成后,而且把ApplicationContextApplicationArguments对象都作为参数进行了传递,那么我们来看看这个方法究竟干了些什么事情?

SpringApplication#callRunners:

private void callRunners(ApplicationContext context, ApplicationArguments args) {
  List<Object> runners = new ArrayList<>();
  runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
  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);
    }
  }
}

我想大家看到这里就应该明白了,这个方法就是在执行CommandLineRunner以及ApplicationRunner实现类实例的#run()方法,首先会从ApplicationContext中获取CommandLineRunnerApplicationRunner接口实现类的实例,然后根据不同类型的Runner实例去调用了callRunner方法。

SpringApplication#callRunner:


// 调用ApplicationRunner实现类实例#run()
private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
  try {
    (runner).run(args);
  }
  catch (Exception ex) {
    throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
  }
}
// 调用CommandLineRunner实现类实例#run()
private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
  try {
    (runner).run(args.getSourceArgs());
  }
  catch (Exception ex) {
    throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
  }
}

设置执行顺序

那如果我们创建了多个CommandLineRunnerApplicationRunner实现类,还想要实现类在执行的时候有一定的先后顺序,那你不妨试下org.springframework.core.annotation.Order这个注解或者实现org.springframework.core.Ordered接口。

CommandLineRunnerExample:

/**
 * {@link CommandLineRunner}接口使用示例
 *
 * @author 恒宇少年
 */
@Component
@Order(100)
public class CommandLineRunnerExample implements CommandLineRunner, Ordered {
    // 省略部分代码
    @Override
    public int getOrder() {
        return 100;
    }
}
接口注解的方式选择其中一种就可以了。
相关文章
|
人工智能 前端开发 测试技术
探索软件测试中的自动化框架选择与优化策略####
本文深入剖析了当前主流的自动化测试框架,通过对比分析各自的优势、局限性及适用场景,为读者提供了一套系统性的选择与优化指南。文章首先概述了自动化测试的重要性及其在软件开发生命周期中的位置,接着逐一探讨了Selenium、Appium、Cypress等热门框架的特点,并通过实际案例展示了如何根据项目需求灵活选用与配置框架,以提升测试效率和质量。最后,文章还分享了若干最佳实践和未来趋势预测,旨在帮助测试工程师更好地应对复杂多变的测试环境。 ####
297 4
|
7月前
|
机器学习/深度学习 弹性计算 固态存储
2025年阿里云服务器租用价格参考:云服务器ECS最新收费标准及活动价格表
2025年,阿里云服务器ECS的租用价格再次迎来更新,1月22日12:00开始,阿里云又开启新一轮的降价政策,部分实例规格的云服务器收费标准有所变化,同时为了进一步降低了用户上云的成本,阿里云还会不定期推出各种活动。现在月付和年付租用阿里云服务器均有优惠了,本文为大家整理汇总了截止目前阿里云服务器最新的租用收费标准及活动价格表,以供了解与参考选择。
3359 10
WordPress 修改上传文件大小限制
WordPress 修改上传文件大小限制
403 3
|
XML JavaScript 前端开发
vue项目中使用bpmn.js详细流程(结合activiti版)
vue项目中使用bpmn.js详细流程(结合activiti版)
2726 0
|
弹性计算 负载均衡 网络协议
slb健康检查
【9月更文挑战第2天】
503 10
|
Java Spring 容器
Spring注解开发,bean的作用范围及生命周期、Spring注解开发依赖注入
Spring注解开发,bean的作用范围及生命周期、Spring注解开发依赖注入
198 1
Spring注解开发,bean的作用范围及生命周期、Spring注解开发依赖注入
|
缓存 Linux iOS开发
【C/C++ 集成内存调试、内存泄漏检测和性能分析的工具 Valgrind 】Linux 下 Valgrind 工具的全面使用指南
【C/C++ 集成内存调试、内存泄漏检测和性能分析的工具 Valgrind 】Linux 下 Valgrind 工具的全面使用指南
1946 1
|
前端开发 NoSQL Java
SpringBoot中application.properties的常用配置
SpringBoot中application.properties的常用配置
|
机器学习/深度学习 算法 PyTorch
【13】变分自编码器(VAE)的原理介绍与pytorch实现
【13】变分自编码器(VAE)的原理介绍与pytorch实现
3305 0
【13】变分自编码器(VAE)的原理介绍与pytorch实现