應(yīng)用啟動(dòng)數(shù)據(jù)初始化接口CommandLineRunner和Application詳解
應(yīng)用啟動(dòng)數(shù)據(jù)初始化接口CommandLineRunner和Application詳解
在SpringBoot項(xiàng)目中創(chuàng)建組件類(lèi)實(shí)現(xiàn)CommandLineRunner或ApplicationRunner接口可實(shí)現(xiàn)在應(yīng)用啟動(dòng)之后及時(shí)進(jìn)行一些初始化操作,如緩存預(yù)熱、索引重建等等類(lèi)似一些數(shù)據(jù)初始化操作。
兩個(gè)接口功能相同,都有個(gè)run方法需要重寫(xiě),只是實(shí)現(xiàn)方法的參數(shù)不同。
CommandLineRunner接收原始的命令行啟動(dòng)參數(shù),ApplicationRunner則將啟動(dòng)參數(shù)對(duì)象化。
1 運(yùn)行時(shí)機(jī)
兩個(gè)接口都是在SpringBoot應(yīng)用初始化好上下文之后運(yùn)行,所以在運(yùn)行過(guò)程中,可以使用上下文中的所有信息,例如一些Bean等等。在框架SpringApplication類(lèi)源碼的run方法中,可查看Runner的調(diào)用時(shí)機(jī)callRunners,如下:
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
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);
//調(diào)用Runner,執(zhí)行初始化操作
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 實(shí)現(xiàn)接口
2.1 CommandLineRunner
簡(jiǎn)單實(shí)現(xiàn)如下,打印啟動(dòng)參數(shù)信息:
@Order(1)
@Component
public class CommandLineRunnerInit implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private final String LOG_PREFIX = ">>>>>>>>>>CommandLineRunner >>>>>>>>>> ";
@Override
public void run(String... args) throws Exception {
try {
this.logger.error("{} args:{}", LOG_PREFIX, StringUtils.join(args, ","));
} catch (Exception e) {
logger.error("CommandLineRunnerInit run failed", e);
}
}
}
2.2 ApplicationRunner
簡(jiǎn)單實(shí)現(xiàn)如下,打印啟動(dòng)參數(shù)信息,并調(diào)用Bean的方法(查詢用戶數(shù)量):
@Order(2)
@Component
public class ApplicationRunnerInit implements ApplicationRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private final String LOG_PREFIX = ">>>>>>>>>>ApplicationRunner >>>>>>>>>> ";
private final UserRepository userRepository;
public ApplicationRunnerInit(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void run(ApplicationArguments args) throws Exception {
try {
this.logger.error("{} args:{}", LOG_PREFIX, JSONObject.toJSONString(args));
for (String optionName : args.getOptionNames()) {
this.logger.error("{} argName:{} argValue:{}", LOG_PREFIX, optionName, args.getOptionValues(optionName));
}
this.logger.error("{} user count:{}", LOG_PREFIX, this.userRepository.count());
} catch (Exception e) {
logger.error("CommandLineRunnerInit run failed", e);
}
}
}
3 執(zhí)行順序
如果實(shí)現(xiàn)了多個(gè)Runner,默認(rèn)會(huì)按照添加順序先執(zhí)行ApplicationRunner的實(shí)現(xiàn)再執(zhí)行CommandLineRunner的實(shí)現(xiàn),如果多個(gè)Runner之間的初始化邏輯有先后順序,可在實(shí)現(xiàn)類(lèi)添加@Order注解設(shè)置執(zhí)行順序,可在源碼SpringApplication類(lèi)的callRunners方法中查看,如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
//先添加的ApplicationRunner實(shí)現(xiàn)
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
//再添加的CommandLineRunner實(shí)現(xiàn)
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
//如果設(shè)置了順序,則按設(shè)定順序重新排序
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);
}
}
}
4 設(shè)置啟動(dòng)參數(shù)
為了便于對(duì)比效果,在Idea中設(shè)置啟動(dòng)參數(shù)如下圖(生產(chǎn)環(huán)境中會(huì)自動(dòng)讀取命令行啟動(dòng)參數(shù)):

5 運(yùn)行效果
在上面的兩個(gè)Runner中,設(shè)定了CommandLineRunnerInit是第一個(gè),ApplicationRunnerInit是第二個(gè)。啟動(dòng)應(yīng)用,運(yùn)行效果如下圖:

ApplicationRunner和CommandLineRunner用法區(qū)別
業(yè)務(wù)場(chǎng)景:
應(yīng)用服務(wù)啟動(dòng)時(shí),加載一些數(shù)據(jù)和執(zhí)行一些應(yīng)用的初始化動(dòng)作。如:刪除臨時(shí)文件,清除緩存信息,讀取配置文件信息,數(shù)據(jù)庫(kù)連接等。
1、SpringBoot提供了CommandLineRunner和ApplicationRunner接口。當(dāng)接口有多個(gè)實(shí)現(xiàn)類(lèi)時(shí),提供了@order注解實(shí)現(xiàn)自定義執(zhí)行順序,也可以實(shí)現(xiàn)Ordered接口來(lái)自定義順序。
注意:數(shù)字越小,優(yōu)先級(jí)越高,也就是@Order(1)注解的類(lèi)會(huì)在@Order(2)注解的類(lèi)之前執(zhí)行。
兩者的區(qū)別在于:
ApplicationRunner中run方法的參數(shù)為ApplicationArguments,而CommandLineRunner接口中run方法的參數(shù)為String數(shù)組。想要更詳細(xì)地獲取命令行參數(shù),那就使用ApplicationRunner接口
ApplicationRunner
@Component
@Order(value = 10)
public class AgentApplicationRun2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
}
}
CommandLineRunner
@Component
@Order(value = 11)
public class AgentApplicationRun implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
}
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解SpringBoot靜態(tài)方法獲取bean的三種方式
本文主要介紹了詳解SpringBoot靜態(tài)方法獲取bean的三種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
tio-boot整合hotswap-classloader實(shí)現(xiàn)熱加載方法實(shí)例
這篇文章主要為大家介紹了tio-boot整合hotswap-classloader實(shí)現(xiàn)熱加載方法實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Java使用Lambda表達(dá)式查找list集合中是否包含某值問(wèn)題
Java使用Lambda表達(dá)式查找list集合中是否包含某值的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06

