Spring Boot 的啟動流程 Run方法


Spring Boot 的啟動流程

1 - 先簡單介紹一下run方法的過程

// 在spring boot中run方法才是啟動應用的實際方法 最終返回的是一個ConfigurableApplicationContext容器
ConfigurableApplicationContext context = SpringApplication.run(SpringbootdemoApplication.class, args);
// 在run方法中 創建了容器 並作了一系列的初始化處理
context = createApplicationContext(); // 創建一個容器對象
context.setApplicationStartup(this.applicationStartup);// 創建一個應用程序監視器
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);// 准備上下文
refreshContext(context);// 刷新上下文 
afterRefresh(context, applicationArguments);// 上下文刷新后

2 -- 首先是 createApplicationContext() 創建一個容器

// 通過調試可以看到最終返回的是 實現了它的 AnnotationConfigServletWebServerApplicationContext web容器
// 之所以是 AnnotationConfigServletWebServerApplicationContext 也是有選擇的 在run方法創建應用容器的時候 根據應用類型來進行創建
switch (webApplicationType) {// 根據的應用程序的類型來進行選擇的 webApplicationType
    case SERVLET:
        return new AnnotationConfigServletWebServerApplicationContext();
    case REACTIVE:
        return new AnnotationConfigReactiveWebServerApplicationContext();
    default:
        return new AnnotationConfigApplicationContext();
}

// 首先進入的是 AnnotationConfigServletWebServerApplicationContext 的構造方法
public AnnotationConfigServletWebServerApplicationContext() {
    this.reader = new AnnotatedBeanDefinitionReader(this); // 首先創建了一個Bean定義閱讀器
    this.scanner = new ClassPathBeanDefinitionScanner(this);// 然后創建了一個Bean掃描器
}// 初次之外沒做別的了

3 -- 其次是 refreshContext(context); 刷新上下文

// 可以看出來 refreshContext 實際上就是調用的容器的refresh方法
private void refreshContext(ConfigurableApplicationContext context) {
    if (this.registerShutdownHook) {
        try {
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
            // Not allowed in some environments.
        }
    }
    refresh(context);
}
protected void refresh(ConfigurableApplicationContext applicationContext) {
    applicationContext.refresh();
}
// 而AnnotationConfigServletWebServerApplicationContext 中沒有 refresh方法
// 所以實際上refreshContext調用的是ServletWebServerApplicationContext的refresh方法
// 而ServletWebServerApplicationContext也並沒有refresh方法
public final void refresh() throws BeansException, IllegalStateException {
    try {
        super.refresh();
    }
    catch (RuntimeException ex) {
        WebServer webServer = this.webServer;
        if (webServer != null) {
            webServer.stop();
        }
        throw ex;
    }
}// 最終調用的還是 老朋友 ApplicationContext 的refresh (refresh 方法就不同介紹了吧)

到此為止 run方法中需要着重介紹的東西也就沒了

簡單整理一下:其實spring boot的啟動流程就是一個創建容器的過程

下面就是根據這個過程整理的一個簡單的流程圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM