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
  • 前言 插件化的需求主要源於對軟體架構靈活性的追求,特別是在開發大型、複雜或需要不斷更新的軟體系統時,插件化可以提高軟體系統的可擴展性、可定製性、隔離性、安全性、可維護性、模塊化、易於升級和更新以及支持第三方開發等方面的能力,從而滿足不斷變化的業務需求和技術挑戰。 一、插件化探索 在WPF中我們想要開 ...
  • 歡迎ReaLTaiizor是一個用戶友好的、以設計為中心的.NET WinForms項目控制項庫,包含廣泛的組件。您可以使用不同的主題選項對項目進行個性化設置,並自定義用戶控制項,以使您的應用程式更加專業。 項目地址:https://github.com/Taiizor/ReaLTaiizor 步驟1: ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • Channel 是乾什麼的 The System.Threading.Channels namespace provides a set of synchronization data structures for passing data between producers and consume ...
  • efcore如何優雅的實現按年分庫按月分表 介紹 本文ShardinfCore版本 本期主角: ShardingCore 一款ef-core下高性能、輕量級針對分表分庫讀寫分離的解決方案,具有零依賴、零學習成本、零業務代碼入侵適配 距離上次發文.net相關的已經有很久了,期間一直在從事java相關的 ...
  • 前言 Spacesniffer 是一個免費的文件掃描工具,通過使用樹狀圖可視化佈局,可以立即瞭解大文件夾的位置,幫助用戶處理找到這些文件夾 當前系統C盤空間 清理後系統C盤空間 下載 Spacesniffer 下載地址:https://spacesniffer.en.softonic.com/dow ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • 一、ReZero簡介 ReZero是一款.NET中間件 : 全網唯一開源界面操作就能生成API , 可以集成到任何.NET6+ API項目,無破壞性,也可讓非.NET用戶使用exe文件 免費開源:MIT最寬鬆協議 , 一直從事開源事業十年,一直堅持開源 1.1 純ReZero開發 適合.Net Co ...
  • 一:背景 1. 講故事 停了一個月沒有更新文章了,主要是忙於寫 C#內功修煉系列的PPT,現在基本上接近尾聲,可以回頭繼續更新這段時間分析dump的一些事故報告,有朋友微信上找到我,說他們的系統出現了大量的http超時,程式不響應處理了,讓我幫忙看下怎麼回事,dump也抓到了。 二:WinDbg分析 ...
  • 開始做項目管理了(本人3年java,來到這邊之後真沒想到...),天天開會溝通整理需求,他們講話的時候忙裡偷閑整理一下常用的方法,其實語言還是有共通性的,基本上看到方法名就大概能猜出來用法。出去打水的時候看到外面太陽好好,真想在外面坐著曬太陽,回來的時候好兄弟三年前送給我的鍵盤D鍵不靈了,在打"等待 ...