第3章 ApplicationRunner 和 CommandLineRunner 服务启动加载配置
SpringBoot 提供了 ApplicationRunner 和 CommandLineRunner 接口,可以用来在服务器启动后,自定义去加载一些配置。例如,我们可以在服务启动后,加载数据库数据等。
使用
我们可以定义多个 ApplicationRunner 或 CommandLineRunner 的实现类。如果想要控制执行的顺序,可以加 @Order() 进行控制。
@Component
public class MetaDataConfigLoader implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("从数据库加载数据成功");
}
}
扩展
除了本篇文章讲的这种方式以外,我们还可以利用 @PostConstruct 、InitializingBean等方法完成初始化工作。
参考:Running Logic on Startup in Spring
源码
只关注 callRunners() 的方法。(其他的我也暂时不懂)
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);
// 调用ApplicationRunner 和 CommandLineRunner
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;
}
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());
// 有多个实现的话,可以根据@Order进行排序
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);
}
}
}
本文详细介绍了Spring Boot中ApplicationRunner和CommandLineRunner接口的使用,这两个接口可在服务启动后执行自定义配置,如加载数据库数据。通过实现这些接口并使用Ordered接口控制执行顺序,可以灵活地进行初始化操作。此外,文章提到了其他启动时运行逻辑的方法,并简单提及了源码分析,重点关注了callRunners方法。
821

被折叠的 条评论
为什么被折叠?



