注:本系列源碼分析基於springboot 2.2.2.RELEASE,對應的spring版本爲5.2.2.RELEASE,源碼的gitee倉庫倉庫地址:funcy/spring-boot.
上一篇文章總結springboot啓動流程如下:
接上文,我們繼續分析接下來的步驟。
3.11 刷新後的處理
刷新後的處理方法爲SpringApplication#afterRefresh
,內容如下:
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}
可以看到,這是一個空方法,springboot提供的擴展。
3.12 發佈started
事件
該操作的方法爲listeners.started(context)
,發佈邏輯前面已經分析過,這裏就不再分析了。
3.13 運行器回調
處理運行器的方法是SpringApplication#callRunners
,代碼如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
// 獲取所有的 ApplicationRunner 與 CommandLineRunner
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
// 排序
AnnotationAwareOrderComparator.sort(runners);
// 遍歷調用
for (Object runner : new LinkedHashSet<>(runners)) {
// 調用 ApplicationRunner#run 方法
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
// 調用 CommandLineRunner#run 方法
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
/**
* 調用 ApplicationRunner#run 方法
*/
private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
try {
(runner).run(args);
}
catch (Exception ex) {
throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
}
}
/**
* 調用 CommandLineRunner#run 方法
*/
private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
try {
(runner).run(args.getSourceArgs());
}
catch (Exception ex) {
throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
}
}
這兩個方法表示,springboot爲我們提供了兩個接口:ApplicationRunner
與CommandLineRunner
,我們可以實現它來完成一些操作,應用示例如下:
/**
* ApplicationRunner 示例
*/
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("MyApplicationRunner: hello world");
}
}
/**
* CommandLineRunner 示例
*/
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("MyCommandLineRunner: hello world!");
}
}
3.14 運行監聽器方法: listeners.running(...)
這個方法的運行同前面分析的listeners.starting()
套路一樣,這裏就不分析了。
好了,本文的分析就到這裏了,關於springboot的啓動流程的分析也到這裏了。
本文原文鏈接:https://my.oschina.net/funcy/blog/4906553 ,限於作者個人水平,文中難免有錯誤之處,歡迎指正!原創不易,商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。