spring boot CommandLineRunner 和ApplicationRunner初始化操作

这两个类都在org.springframework.boot下,也就是说这是springboot新增的,是为了在容器启动之后做一些初始化的操作。
org.springframework.boot.CommandLineRunner
org.springframework.boot.ApplicationRunner

区别

这两个接口的区别是,run方法的参数不同,ApplicationRunner的run方法参数是ApplicationArguments,而CommandLineRunner是一个String数组。
所以在调用的时候是(ApplicationRunner)runner.run(args);(CommandLineRunner)runner.run(args.getSourceArgs());的区别。

@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;

}
@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;

}

调用runner的源码解析

SpringBoot的启动是调用SpringApplication.run方法,run方法中有一个callRunners方法,调用它callRunners(context, applicationArguments);就实现了调用所有ApplicationRunner和CommandLineRunner的步骤。

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);
        }
    }
}

private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
    try {
        (runner).run(args);
    }
    catch (Exception ex) {
        throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
    }
}

private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
    try {
        (runner).run(args.getSourceArgs());
    }
    catch (Exception ex) {
        throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
    }
}

使用场景

  1. https://blog.csdn.net/lk142500/article/details/90270592
  2. 系统初始化时对一些数据库进行操作,如固定生成一些账号。
上一页 -