day03-分析SpringBoot底層機制

来源:https://www.cnblogs.com/liyuelian/archive/2023/03/14/17216473.html
-Advertisement-
Play Games

分析SpringBoot底層機制 Tomcat啟動分析,Spring容器初始化,Tomcat如何關聯Spring容器? 1.創建SpringBoot環境 (1)創建Maven程式,創建SpringBoot環境 (2)pom.xml導入SpringBoot的父工程和依賴 <!--導入SpringBoo ...


分析SpringBoot底層機制

Tomcat啟動分析,Spring容器初始化,Tomcat如何關聯Spring容器?

1.創建SpringBoot環境

(1)創建Maven程式,創建SpringBoot環境

(2)pom.xml導入SpringBoot的父工程和依賴

<!--導入SpringBoot父工程-規定寫法-->
<parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.5.3</version>
</parent>
<dependencies>
    <!--導入web項目場景啟動器:會自動導入和web開發相關的所有依賴[jar包]-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

(3)創建主程式MainApp.java

package com.li.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author 李
 * @version 1.0
 */
@SpringBootApplication//表示SpringBoot項目
public class MainApp {
    public static void main(String[] args) {
        //啟動SpringBoot項目
        ConfigurableApplicationContext ioc =
                SpringApplication.run(MainApp.class, args);
    }
}

(4)啟動項目,我們可以註意到Tomcat也隨之啟動了。

image-20230314175853668

問題一:當我們執行run方法時,為什麼會啟動我們內置的tomcat?它的底層是如何實現的?

2.Spring容器初始化(@Configuration+@Bean)

我們知道,如果在一個類上添加了註解@Configuration,那麼這個類就會變成配置類;配置類中通過@Bean註解,可以將方法中 new 出來的Bean對象註入到容器中,該bean對象的id預設為方法名。

配置類本身也會作為bean註入到容器中

image-20230314183308566

容器初始化的底層機制仍然是我們之前分析的Spring容器的機制(IO/文件掃描+註解+反射+集合+映射)

對比:

  1. Spring通過@ComponentScan,指定要掃描的包;而SpringBoot預設從主程式所在的包開始掃描,同時也可以指定要掃描的包(scanBasePackages = {"xxx.xx"})。
  2. Spring通過xml或者註解,指定要註入的bean;SpringBoot通過掃描配置類(對應spring的xml)的@Bean或者註解,指定註入bean

3.SpringBoot怎樣啟動Tomcat,並能支持訪問@Controller?

由前面的例子1中可以看到,當啟動SpringBoot時,tomcat也會隨之啟動。那麼問題來了:

  1. SpringBoot是怎麼內嵌Tomcat,並啟動Tomcat的?
  2. 而且底層是怎樣讓@Controller修飾的控制器也可以被訪問的?

3.1源碼分析SpringApplication.run()

SpringApplication.run()方法會完成兩個重要任務:

  1. 創建容器
  2. 容器的刷新:包括參數的刷新+啟動Tomcat

(1)創建一個控制器

package com.li.springboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 李
 * @version 1.0
 * HiController被標註後,作為一個控制器註入容器中
 */
@RestController//相當於@Controller+@ResponseBody
public class HiController {

    @RequestMapping("/hi")
    public String hi() {
        return "hi,HiController";
    }
}

(2)啟動主程式MainApp.java,進行debug

image-20230314195800999

(3)首先進入SpringApplication.java的run方法

image-20230314201959442

(4)點擊step into,進入如下方法

public ConfigurableApplicationContext run(String... args) {
    ...
    try {
        ...
        context = this.createApplicationContext();//嚴重分析,創建容器
        context.setApplicationStartup(this.applicationStartup);
        this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
        this.refreshContext(context);//刷新應用上下文,比如初始化預設設置/註入相關bean/啟動Tomcat
        this.afterRefresh(context, applicationArguments);
        stopWatch.stop();
        ...

    } catch (Throwable var10) {...}
    ...
}

(5)分別對 **createApplicationContext() **和 refreshContext(context) 方法進行分析:

(5.1)step into 進入 **createApplicationContext() ** 方法中:

//springApplication.java
//容器類型很多,會根據你的this.webApplicationType創建對應的容器,預設this.webApplicationType
//的類型為SERVLET,也就是web容器(可以處理servlet)
protected ConfigurableApplicationContext createApplicationContext() {
    return this.applicationContextFactory.create(this.webApplicationType);
}
image-20230314203013719

(5.2)點擊進入下一層

//介面 ApplicationContextFactory.java

//該方法根據webApplicationType創建不同的容器
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
    try {
        switch(webApplicationType) {
        case SERVLET://預設進入這一分支,返回
                //AnnotationConfigServletWebServerApplicationContext容器
            return new AnnotationConfigServletWebServerApplicationContext();
        case REACTIVE:
            return new AnnotationConfigReactiveWebServerApplicationContext();
        default:
            return new AnnotationConfigApplicationContext();
        }
    } catch (Exception var2) {
        throw new IllegalStateException("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2);
    }
};

總結:createApplicationContext()方法中創建了容器,但是還沒有將bean註入到容器中。

(5.3)step into 進入 refreshContext(context) 方法中:

//springApplication.java
private void refreshContext(ConfigurableApplicationContext context) {
    if (this.registerShutdownHook) {
        shutdownHook.registerApplicationContext(context);
    }

    this.refresh(context);//核心,真正執行相關任務
}

(5.4)在this.refresh(context);這一步進入下一層:

//springApplication.java
protected void refresh(ConfigurableApplicationContext applicationContext) {
    applicationContext.refresh();
}

(5.5)繼續進入下一層:

protected void refresh(ConfigurableApplicationContext applicationContext) {
    applicationContext.refresh();
}

(5.6)繼續進入下一層:

//ServletWebServerApplicationContext.java
public final void refresh() throws BeansException, IllegalStateException {
    try {
        super.refresh();
    } catch (RuntimeException var3) {
        WebServer webServer = this.webServer;
        if (webServer != null) {
            webServer.stop();
        }

        throw var3;
    }
}

(5.7)在super.refresh();這一步進入下一層:

//AbstractApplicationContext.java

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
     ...
      try {
        ...
         // Initialize other special beans in specific context subclasses.
         //在上下文的子類初始化指定的bean
         onRefresh(); //當父類完成通用的工作後,再重新用動態綁定機制回到子類
        ...
      }

      catch (BeansException ex) {...}

      finally {...}
   }
}

(5.8)在onRefresh();這一步step into,會重新返回上一層:

//ServletWebServerApplicationContext.java
protected void onRefresh() {
    super.onRefresh();

    try {
        this.createWebServer();//創建一個webserver,可以理解成創建我們指定的web服務-Tomcat
    } catch (Throwable var2) {
        throw new ApplicationContextException("Unable to start web server", var2);
    }
}

(5.9)在this.createWebServer();這一步step into:

//ServletWebServerApplicationContext.java

private void createWebServer() {
    WebServer webServer = this.webServer;
    ServletContext servletContext = this.getServletContext();
    if (webServer == null && servletContext == null) {
        StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
        ServletWebServerFactory factory = this.getWebServerFactory();
        createWebServer.tag("factory", factory.getClass().toString());
        this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});//使用TomcatServletWebServerFactory創建一個TomcatWebServer
        createWebServer.end();
        this.getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer));
        this.getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, this.webServer));
    } else if (servletContext != null) {
        try {
            this.getSelfInitializer().onStartup(servletContext);
        } catch (ServletException var5) {
            throw new ApplicationContextException("Cannot initialize servlet context", var5);
        }
    }

    this.initPropertySources();
}
image-20230314205608658

(5.10)在this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});這一步step into:

//TomcatServletWebServerFactory.java會創建Tomcat,並啟動Tomcat

public WebServer getWebServer(ServletContextInitializer... initializers) {
    if (this.disableMBeanRegistry) {
        Registry.disableRegistry();
    }

    Tomcat tomcat = new Tomcat();//創建了Tomcat對象,下麵是一系列的初始化任務
    File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
    tomcat.setBaseDir(baseDir.getAbsolutePath());
    Connector connector = new Connector(this.protocol);
    connector.setThrowOnFailure(true);
    tomcat.getService().addConnector(connector);
    this.customizeConnector(connector);
    tomcat.setConnector(connector);
    tomcat.getHost().setAutoDeploy(false);
    this.configureEngine(tomcat.getEngine());
    Iterator var5 = this.additionalTomcatConnectors.iterator();

    while(var5.hasNext()) {
        Connector additionalConnector = (Connector)var5.next();
        tomcat.getService().addConnector(additionalConnector);
    }

    this.prepareContext(tomcat.getHost(), initializers);
    return this.getTomcatWebServer(tomcat);
}

(5.11)在return this.getTomcatWebServer(tomcat);這一步step into:

//TomcatServletWebServerFactory.java

//這裡做了埠校驗,創建了TomcatWebServer
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
    return new TomcatWebServer(tomcat, this.getPort() >= 0, this.getShutdown());
}

(5.12)繼續step into進入下一層

//TomcatServletWebServerFactory.java

public TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {
    this.monitor = new Object();
    this.serviceConnectors = new HashMap();
    Assert.notNull(tomcat, "Tomcat Server must not be null");
    this.tomcat = tomcat;
    this.autoStart = autoStart;
    this.gracefulShutdown = shutdown == Shutdown.GRACEFUL ? new GracefulShutdown(tomcat) : null;
    this.initialize();//進行初始化,並啟動tomcat
}

(5.13)this.initialize();繼續step into:

//TomcatServletWebServerFactory.java

private void initialize() throws WebServerException {
    logger.info("Tomcat initialized with port(s): " + this.getPortsDescription(false));
    synchronized(this.monitor) {
        try {
            this.addInstanceIdToEngineName();
            Context context = this.findContext();
            context.addLifecycleListener((event) -> {
                if (context.equals(event.getSource()) && "start".equals(event.getType())) {
                    this.removeServiceConnectors();
                }

            });
            this.tomcat.start();//啟動Tomcat!
            this.rethrowDeferredStartupExceptions();

            try {
                ContextBindings.bindClassLoader(context, context.getNamingToken(), this.getClass().getClassLoader());
            } catch (NamingException var5) {
            }

            this.startDaemonAwaitThread();
        } catch (Exception var6) {
            this.stopSilently();
            this.destroySilently();
            throw new WebServerException("Unable to start embedded Tomcat", var6);
        }

    }
}

(6)一路返回上層,然後終於執行完refreshContext(context)方法,此時context為已經註入了bean

image-20230314211332259
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 山海鯨可視化創造了一種CS和BS熱切換的編輯模式,即CSaaS架構,可以在安裝軟體之後一鍵從軟體的CS狀態切換為一個BS伺服器,讓私有化部署變得十分輕鬆。在視頻中我們先在CS模式下的軟體中進行了編輯,隨後熱切換到BS模式下的web中依然可以在幾乎完全相同的體驗下進行編輯。 ...
  • 代理模式(Proxy Pattern):前端設計模式中的代理模式是一種結構型模式,它允許在不改變原始對象的情況下,通過引入一個代理對象來控制對原始對象的訪問。代理對象充當原始對象的中介,客戶端與代理對象交互,代理對象再將請求轉發給原始對象。 代理模式在前端開發中經常被用來處理一些複雜或者耗時的操作, ...
  • 第一部分 類型和語法 第一章 類型 JavaScript 有七種內置類型: • 空值(null) • 未定義(undefined) • 布爾值( boolean) • 數字(number) • 字元串(string) • 對象(object) • 符號(symbol,ES6 中新增) typeof ...
  • 觀察者模式 介紹 觀察者模式是極其重要的一個設計模式,在許多框架都使用了,以及實際開發中也會用到。 定義對象之間的一種一對多的依賴關係,使得每當一個對象的狀態發生變化時,其相關的依賴對象都可以得到通知並被自動更新。主要用於多個不同的對象對一個對象的某個方法會做出不同的反應! 以不同觀察者從同一個天氣 ...
  • 故障無處不在,而且無法避免。(分散式計算謬誤) 在分散式系統建設的過程中,我們思考的重點不是避免故障,而是擁抱故障,通過構建高可用架構體系來獲得優雅應對故障的能力。QQ音樂高可用架構體系包含三個子系統:架構、工具鏈和可觀測性。 ...
  • 1. 元空間(metaspace) 1.1. 當JVM載入類時,它必須記錄這些類的某些元數據,這些數據占據的一個單獨的堆空間,即元空間 1.2. 元空間里的信息只在編譯器和JVM運行時使用,它所保存的數據被稱為類元數據(class metadata) 1.2.1. 對於終端用戶,元空間是不透明的 1 ...
  • 指針:是一個變數,存儲一個變數的地址。 引用:是變數的別名。 1、初始化 指針定義時不必初始化,引用必須初始化。 指針初始化時可為NULL,引用不能初始化為NULL。 int a = 10; int *p = &a; int &y = a; cout << "a是" << a << endl; co ...
  • 1、回顧MVC 1.1、什麼是MVC MVC是模型(Model)、視圖(View)、控制器(Controller)的簡寫,是一種軟體設計規範。 是將業務邏輯、數據、顯示分離的方法來組織代碼。 MVC主要作用是降低了視圖與業務邏輯間的雙向偶合。 MVC不是一種設計模式,MVC是一種架構模式。當然不同的 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...