首頁  >  文章  >  Java  >  SpringBoot嵌入式Web容器如何使用

SpringBoot嵌入式Web容器如何使用

PHPz
PHPz轉載
2023-05-13 23:34:041431瀏覽

嵌入式Web 容器:應用程式內建伺服器(Tomcat),不用在外部設定伺服器了

原理

  • SpringBoot 專案啟動,發現是web 應用,引入web 場景包----- 如:Tomcat

  • web 應用程式建立一個web 版的IOC 容器ServletWebServerApplicationContext

  • #ServletWebServerApplicationContext 啟動的時候尋找ServletWebServerFactory (Servlet 的web 伺服器工廠,用於生產Servlet 伺服器)

  • ServletWebServerFactory 底層預設有很多Web 伺服器工廠

SpringBoot嵌入式Web容器如何使用

  • 底層會自動設定好,自動設定類別ServletWebServerFactoryAutoConfiguration

  • ServletWebServerFactoryAutoConfiguration 匯入ServletWebServer#yConfiguration 工廠配置類別

1類別類別

#ServletWebServerFactoryConfiguration.classSpringBoot嵌入式Web容器如何使用

  • #動態判斷系統中匯入了那個網頁伺服器設定套件
  • 如果導入Tomcat 依賴,會自動放置一個Tomcat 伺服器工廠, TomcatServletWebServerFactory 為我們創建出Tomcat 伺服器工廠
  • Tomcat 底層支援如下伺服器

SpringBoot嵌入式Web容器如何使用

Tomcat 底層支援如下伺服器

Tomcat 底層支援如下伺服器

#

	@Override
	public WebServer getWebServer(ServletContextInitializer... initializers) {
		if (this.disableMBeanRegistry) {
			Registry.disableRegistry();
		}
		Tomcat tomcat = new Tomcat();
		File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
		tomcat.setBaseDir(baseDir.getAbsolutePath());
		Connector connector = new Connector(this.protocol);
		connector.setThrowOnFailure(true);
		tomcat.getService().addConnector(connector);
		customizeConnector(connector);
		tomcat.setConnector(connector);
		tomcat.getHost().setAutoDeploy(false);
		configureEngine(tomcat.getEngine());
		for (Connector additionalConnector : this.additionalTomcatConnectors) {
			tomcat.getService().addConnector(additionalConnector);
		}
		prepareContext(tomcat.getHost(), initializers);
		return getTomcatWebServer(tomcat);
	}
SpringBoot嵌入式Web容器如何使用 總結: 所謂內嵌伺服器,就是把我們手動啟動伺服器的方法放進框架裡了。

應用程式

1. 切換Web伺服器

排除tomcat 伺服器,匯入undertow 依賴

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

2. 客製化伺服器規則

#方法一:修改server 下的設定檔

ServerProperties.class

################server.undertow.accesslog.dir=/tmp##### ####方法二: 自訂ConfigurableServletWebServerFactory######方法三: 自訂ServletWebServerFactoryCustomizer 客製化器######作用: 將設定檔的值,與ServletWebServerFactory 綁定設計: Customizer 客製化器,可自訂XXX 規則###

以上是SpringBoot嵌入式Web容器如何使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除