天天看點

SpringBoot原理剖析

SpringBoot啟動過程

  • 第一步: 建立SpringApplication
  • 儲存一些資訊。
  • 判定目前應用的類型。【ClassUtils判斷。一般為Servlet應用】
  • bootstrappers:初始啟動引導器(List<Bootstrapper>):去spring.factories檔案中找 org.springframework.boot.Bootstrapper
  • 找ApplicationContextInitializer;去spring.factories找 ApplicationContextInitializer
  • List<ApplicationContextInitializer<?>>initializers
  • 找 ApplicationListener  ;應用監聽器。去spring.factories找 ApplicationListener
  • List<ApplicationListener<?>>listeners
  • 第二步: 運作S pringApplication
  • StopWatch
  • 記錄應用的啟動時間
  • 建立引導上下文(Context環境)createBootstrapContext()
  • 擷取到所有之前的 bootstrappers 挨個執行 intitialize() 來完成對引導啟動器上下文環境設定
  • 讓目前應用進入headless模式。java.awt.headless
  • 擷取所有 RunListener(運作監聽器)【為了友善所有Listener進行事件感覺】
  • getSpringFactoriesInstances 去spring.factories找 SpringApplicationRunListener.
  • 周遊 SpringApplicationRunListener 調用 starting 方法;
  • 相當于通知所有感興趣系統正在啟動過程的人,項目正在 starting。
  • 儲存指令行參數;ApplicationArguments
  • 準備環境 prepareEnvironment();
  • 傳回或者建立基礎環境資訊對象。StandardServletEnvironment
  • 配置環境資訊對象。
  • 讀取所有的配置源的配置屬性值。
  • 綁定環境資訊
  • 監聽器調用 listener.environmentPrepared();通知所有的監聽器目前環境準備完成
  • 建立IOC容器(createApplicationContext())
  • 根據項目類型(Servlet)建立容器,
  • 目前會建立AnnotationConfigServletWebServerApplicationContext
  • 準備ApplicationContext IOC容器的基本資訊 prepareContext()
  • 儲存環境資訊
  • IOC容器的後置處理流程。
  • 應用初始化器;applyInitializers;
  • 周遊所有的 ApplicationContextInitializer 。調用 initialize.。來對ioc容器進行初始化擴充功能
  • 周遊所有的 listener 調用 contextPrepared。EventPublishRunListenr;通知所有的監聽器contextPrepared
  • 所有的監聽器 調用 contextLoaded。通知所有的監聽器 contextLoaded;
  • 重新整理IOC容器。refreshContext
  • 建立容器中的所有元件(Spring注解)
  • 容器重新整理完成後工作?afterRefresh
  • 所有監聽 器 調用 listeners.started(context); 通知所有的監聽器 started
  • 調用所有runners;callRunners()
  • 擷取容器中的ApplicationRunner
  • 擷取容器中的  CommandLineRunner
  • 合并所有runner并且按照@Order進行排序
  • 周遊所有的runner。調用 run 方法
  • 如果以上有異常,
  • 調用Listener 的 failed
  • 調用所有監聽器的 running 方法  listeners.running(context); 通知所有的監聽器 running
  • running如果有問題。繼續通知 failed 。調用所有 Listener 的 failed;通知所有的監聽器 failed
public interface Bootstrapper {

  /**
   * Initialize the given {@link BootstrapRegistry} with any required registrations.
   * @param registry the registry to initialize
   */
  void intitialize(BootstrapRegistry registry);

}      
SpringBoot原理剖析
@FunctionalInterface
public interface ApplicationRunner {

  /**
   * Callback used to run the bean.
   * @param args incoming application arguments
   * @throws Exception on error
   */
  void run(ApplicationArguments args) throws Exception;

}      
@FunctionalInterface
public interface CommandLineRunner {

  /**
   * Callback used to run the bean.
   * @param args incoming main method arguments
   * @throws Exception on error
   */
  void run(String... args) throws Exception;

}