這篇文章主要講解了“CommandLineRunner和Application怎么使用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“CommandLineRunner和Application怎么使用”吧!
在SpringBoot項目中創建組件類實現CommandLineRunner或ApplicationRunner接口可實現在應用啟動之后及時進行一些初始化操作,如緩存預熱、索引重建等等類似一些數據初始化操作。
兩個接口功能相同,都有個run方法需要重寫,只是實現方法的參數不同。
CommandLineRunner接收原始的命令行啟動參數,ApplicationRunner則將啟動參數對象化。
兩個接口都是在SpringBoot應用初始化好上下文之后運行,所以在運行過程中,可以使用上下文中的所有信息,例如一些Bean等等。在框架SpringApplication類源碼的run方法中,可查看Runner的調用時機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);
//調用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.1 CommandLineRunner
簡單實現如下,打印啟動參數信息:
@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
簡單實現如下,打印啟動參數信息,并調用Bean的方法(查詢用戶數量):
@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);
}
}
}如果實現了多個Runner,默認會按照添加順序先執行ApplicationRunner的實現再執行CommandLineRunner的實現,如果多個Runner之間的初始化邏輯有先后順序,可在實現類添加@Order注解設置執行順序,可在源碼SpringApplication類的callRunners方法中查看,如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
//先添加的ApplicationRunner實現
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
//再添加的CommandLineRunner實現
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);
}
}
}為了便于對比效果,在Idea中設置啟動參數如下圖(生產環境中會自動讀取命令行啟動參數):

在上面的兩個Runner中,設定了CommandLineRunnerInit是第一個,ApplicationRunnerInit是第二個。啟動應用,運行效果如下圖:

業務場景:
應用服務啟動時,加載一些數據和執行一些應用的初始化動作。如:刪除臨時文件,清除緩存信息,讀取配置文件信息,數據庫連接等。
1、SpringBoot提供了CommandLineRunner和ApplicationRunner接口。當接口有多個實現類時,提供了@order注解實現自定義執行順序,也可以實現Ordered接口來自定義順序。
注意:數字越小,優先級越高,也就是@Order(1)注解的類會在@Order(2)注解的類之前執行。
兩者的區別在于:
ApplicationRunner中run方法的參數為ApplicationArguments,而CommandLineRunner接口中run方法的參數為String數組。想要更詳細地獲取命令行參數,那就使用ApplicationRunner接口
@Component
@Order(value = 10)
public class AgentApplicationRun2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
}
}@Component
@Order(value = 11)
public class AgentApplicationRun implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
}
}感謝各位的閱讀,以上就是“CommandLineRunner和Application怎么使用”的內容了,經過本文的學習后,相信大家對CommandLineRunner和Application怎么使用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。