欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot嵌入式Servlet容器與定制化組件超詳細講解

 更新時間:2022年10月03日 10:56:42   作者:Decade0712  
這篇文章主要介紹了SpringBoot嵌入式Servlet容器與定制化組件的使用介紹,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧

嵌入式Servlet容器

在Spring Boot中,默認支持的web容器有 Tomcat, Jetty, 和 Undertow

1、原理分析

那么這些web容器是怎么注入的呢?我們一起來分析一下

當SpringBoot應(yīng)用啟動發(fā)現(xiàn)當前是Web應(yīng)用,它會創(chuàng)建一個web版的ioc容器ServletWebServerApplicationContext

這個類下面有一個createWebServer()方法,當執(zhí)行關(guān)鍵代碼ServletWebServerFactory factory = this.getWebServerFactory();時,它會在系統(tǒng)啟動的時候?qū)ふ?ServletWebServerFactory(Servlet 的web服務(wù)器工廠—> 用于生產(chǎn)Servlet 的web服務(wù)器)

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");
        // 獲取ServletWebFactory
        ServletWebServerFactory factory = this.getWebServerFactory();
        createWebServer.tag("factory", factory.getClass().toString());
        // 這里會去調(diào)用系統(tǒng)中獲取到的web容器工廠類的getWebServer()方法
        this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
        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();
}

獲取ServletWebFactory

protected ServletWebServerFactory getWebServerFactory() {
    String[] beanNames = this.getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
    if (beanNames.length == 0) {
        throw new MissingWebServerFactoryBeanException(this.getClass(), ServletWebServerFactory.class, WebApplicationType.SERVLET);
    } else if (beanNames.length > 1) {
        throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
    } else {
        return (ServletWebServerFactory)this.getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
    }
}

SpringBoot底層默認有很多的WebServer工廠:TomcatServletWebServerFactory,,JettyServletWebServerFactoryUndertowServletWebServerFactory

那么究竟返回哪一個工廠呢?

我們需要分析一下底層的自動配置類,ServletWebServerFactoryAutoConfiguration

@AutoConfiguration
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@EnableConfigurationProperties({ServerProperties.class})
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {
    public ServletWebServerFactoryAutoConfiguration() {
    }
    ...

它引入了一個配置類ServletWebServerFactoryConfiguration,這個類里面會根據(jù)動態(tài)判斷系統(tǒng)中到底導(dǎo)入了那個Web服務(wù)器的包,然后去創(chuàng)建對應(yīng)的web容器工廠,spring-boot-starter-web這個依賴默認導(dǎo)入tomcat,所以我們系統(tǒng)會創(chuàng)建TomcatServletWebServerFactory,由這個工廠創(chuàng)建tomcat容器并啟動

一旦我們獲取到web Server的工廠類,createWebServer()方法就會去調(diào)用this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});

根據(jù)斷點一直深入,我們可以發(fā)現(xiàn),Tomcat, Jetty, 和 Undertow的工廠類最后都會去調(diào)用getWebServer()方法,設(shè)置了鏈接參數(shù),例如TomcatServletWebServerFactorygetWebServer()方法

在方法的最后,它會執(zhí)行return this.getTomcatWebServer(tomcat);,跟著斷點深入,我們發(fā)現(xiàn)它會去調(diào)用對應(yīng)web容器類的構(gòu)造方法,如TomcatWebServer的構(gòu)造方法,啟動tomcat容器

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;
    // 初始化方法initialize---會調(diào)用this.tomcat.start();啟動容器
    this.initialize();
}

2、Servlet容器切換

Spring Boot默認使用的是tomcat容器,那如果我們想要使用Undertow應(yīng)該如何切換呢

只需要修改pom文件即可,排除web啟動器中tomcat相關(guān)的依賴

然后導(dǎo)入Undertow相關(guān)啟動器

<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>

3、定制Servlet容器配置

如果想要自己定義一個Servlet容器,可以通過哪些途徑呢?

  • 通過分析ServletWebServerFactoryAutoConfiguration綁定了ServerProperties配置類可知,我們想要修改容器的配置,只需要修改配置文件中對應(yīng)的server.xxx配置項即可
  • 創(chuàng)建一個配置類,通過@Configuration+@Bean的方式,向容器中注入一個ConfigurableServletWebServerFactory類的實現(xiàn)類,ConfigurableServletWebServerFactoryServletWebServerFactory類的子類,提供了很多方法供我們使用

代碼樣例如下

package com.decade.config;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
    @Bean
    public ConfigurableServletWebServerFactory defineWebServletFactory() {
        final TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory();
        tomcatServletWebServerFactory.setPort(8081);
        return tomcatServletWebServerFactory;
    }
}

自定義一個ServletWebServerFactoryCustomizer類,它的下面有一個customize()方法,能把配置文件的值和ServletWebServerFactory 進行綁定

Spring官網(wǎng)提供的樣例如下

Spring中有很多xxxxxCustomizer,它的作用是定制化器,可以改變xxxx的默認規(guī)則

定制化組件

結(jié)合之前的原理分析過程可知,我們分析一個組件的過程可以概括為:

導(dǎo)入對應(yīng)啟動器xxx-starter---->分析xxxAutoConfiguration---->導(dǎo)入xxx組件---->綁定xxxProperties配置類----->綁定配置項

那么如果我們要定制化組件,例如自定義參數(shù)解析器或者應(yīng)用啟動端口等,可以怎么做呢?

  • 修改配置文件 server.xxx
  • 參考上面編寫一個xxxxxCustomizer類
  • 編寫自定義的配置類xxxConfiguration:使用@Configuration + @Bean替換、增加容器中默認組件
  • 如果是Web應(yīng)用,編寫一個配置類實現(xiàn)WebMvcConfigurer接口,重寫對應(yīng)方法即可定制化web功能,或者使用@Bean給容器中再擴展一些組件(這條是最重要的)

注意:@EnableWebMvc + 實現(xiàn)WebMvcConfigurer接口:配置類中定義的@Bean可以全面接管SpringMVC,所有規(guī)則全部自己重新配置

原理:

  • WebMvcAutoConfiguration類是SpringMVC的自動配置功能類。配置了靜態(tài)資源、歡迎頁…
  • 一旦使用@EnableWebMvc會,@Import(DelegatingWebMvcConfiguration.class)

DelegatingWebMvcConfiguration類的作用是:只保證SpringMVC最基本的使用

  • public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport表明它是WebMvcConfigurationSupport的子類
  • 它會把所有系統(tǒng)中的 WebMvcConfigurer的實現(xiàn)類拿過來,所有功能的定制都是這些WebMvcConfigurer的實現(xiàn)類合起來一起生效

WebMvcConfigurationSupport自動配置了一些非常底層的組件,例如RequestMappingHandlerMapping,這些組件依賴的其他組件都是從容器中獲取的,例如ContentNegotiationManager等

由代碼可知,WebMvcAutoConfiguration里面的配置要能生效必須系統(tǒng)中不存在WebMvcConfigurationSupport類,所以,一旦配置類上加了@EnableWebMvc,就會導(dǎo)致WebMvcAutoConfiguration沒有生效

到此這篇關(guān)于SpringBoot嵌入式Servlet容器與定制化組件超詳細講解的文章就介紹到這了,更多相關(guān)SpringBoot Servlet容器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java基礎(chǔ)-Java的體系結(jié)構(gòu)

    Java基礎(chǔ)-Java的體系結(jié)構(gòu)

    這篇文章主要介紹了Java的體系結(jié)構(gòu),Java幾乎成為了“開源”的代名詞。第三方開源軟件和框架。如Tomcat、Struts,MyBatis,Spring等,下面我們來看看文章具體的內(nèi)容介紹吧
    2022-01-01
  • 從Hello?World開始理解GraphQL背后處理及執(zhí)行過程

    從Hello?World開始理解GraphQL背后處理及執(zhí)行過程

    這篇文章主要為大家介紹了從Hello?World開始理解GraphQL背后處理過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • SpringBoot如何實現(xiàn)文件下載

    SpringBoot如何實現(xiàn)文件下載

    這篇文章主要介紹了SpringBoot如何實現(xiàn)文件下載問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • SpringBoot中使用@Async注解失效場景及說明

    SpringBoot中使用@Async注解失效場景及說明

    在Spring?Boot中,@Async注解就像一把刀,能幫你輕松處理那些耗時的任務(wù),讓主線程可以繼續(xù)忙別的事兒,不過,跟所有強大的工具一樣,用不好它也可能出岔子,為了避免這些坑,咱們得深入了解下@Async注解,接下來,咱們就來聊聊7種常見的@Async失效情況,需要的朋友可以參考下
    2024-07-07
  • Java中的自旋鎖與阻塞鎖詳解

    Java中的自旋鎖與阻塞鎖詳解

    這篇文章主要介紹了Java中的自旋鎖與阻塞鎖詳解,阻塞鎖是指當線程嘗試獲取鎖失敗時,線程進入阻塞狀態(tài),直到接收信號后被喚醒,阻塞或者喚醒一個Java線程需要操作系統(tǒng)切換CPU?狀態(tài)來完成,這種狀態(tài)轉(zhuǎn)換?需要耗費處理器時間,需要的朋友可以參考下
    2023-10-10
  • SpringBoot+MyBatisPlus中樂觀鎖的實現(xiàn)示例

    SpringBoot+MyBatisPlus中樂觀鎖的實現(xiàn)示例

    樂觀鎖是一種用于解決并發(fā)沖突的機制,在數(shù)據(jù)庫中用于保護數(shù)據(jù)的一致性,本文主要介紹了SpringBoot+MyBatisPlus中樂觀鎖的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • Java基于Semaphore構(gòu)建阻塞對象池

    Java基于Semaphore構(gòu)建阻塞對象池

    這篇文章主要介紹了Java基于Semaphore構(gòu)建阻塞對象池,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • Java通過導(dǎo)出超大Excel文件解決內(nèi)存溢出問題

    Java通過導(dǎo)出超大Excel文件解決內(nèi)存溢出問題

    導(dǎo)出excel是咱Java開發(fā)的必備技能,下面這篇文章主要給大家介紹了關(guān)于Java通過導(dǎo)出超大Excel文件解決內(nèi)存溢出問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2021-09-09
  • java 算法之快速排序?qū)崿F(xiàn)代碼

    java 算法之快速排序?qū)崿F(xiàn)代碼

    這篇文章主要介紹了java 算法之快速排序?qū)崿F(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • Java 實戰(zhàn)項目之小說在線閱讀系統(tǒng)的實現(xiàn)流程

    Java 實戰(zhàn)項目之小說在線閱讀系統(tǒng)的實現(xiàn)流程

    讀萬卷書不如行萬里路,只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實現(xiàn)前臺閱讀后臺管理的小說在線閱讀系統(tǒng),大家可以在過程中查缺補漏,提升水平
    2021-11-11

最新評論