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

知识改变命运,撸码使我快乐,2020继续游走在开源界

点赞再看,养成习惯

给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案

如果你想要使用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;
    }
}

接口注解的方式选择其中一种就可以了。

作者个人 博客
使用开源框架 ApiBoot 助你成为Api接口服务架构师

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260