1.CommandLineRunner&ApplicationRunner的作用
实现这两个接口的代码会在项目初始化完毕启动之前执行,一般用来加载数据库的初始化的一些配置信息,在springBoot的启动代码中可以看到callRunners是在服务器对外服务前执行的。
在用CommandLineRunner做扩展时需要注意的是当服务已经启动完成,这时CommandLineRunner里的内容可能还没有初始化完成,需要考虑对应用的影响。
@PostConstruct注解是在Bean实例化时调用,调用时间在CommandLineRunner之前,初始化缓存数据可以考虑使用该注解。
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.CommandLineRunner&ApplicationRunner的区别
public class ApplicationRunnerTest implements ApplicationRunner {
@Override
//用于接受启动时传入的参数,也就是java -DXXX之类的
public void run(ApplicationArguments args) throws Exception {
}
}
public class CommandLineRunnerTest implements CommandLineRunner {
@Override
//查看源码,这里的参数是ApplicationArguments 里的一部分,
//是原始未处理的数据
//Return the raw unprocessed arguments that were passed to the application.
public void run(String... args) throws Exception {
System.out.println(10);
}
}
3.如何使用以及注意点
* Interface used to indicate that a bean should <em>run</em> when it is contained within
* a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
* within the same application context and can be ordered using the {@link Ordered}
* interface or {@link Order @Order} annotation.
* <p>
* If you need access to {@link ApplicationArguments} instead of the raw String array
* consider using {@link ApplicationRunner}.