SpringBoot嵌入式Servlet容器與定制化組件超詳細講解
嵌入式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
,,JettyServletWebServerFactory
和 UndertowServletWebServerFactory
那么究竟返回哪一個工廠呢?
我們需要分析一下底層的自動配置類,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ù),例如TomcatServletWebServerFactory
的getWebServer()
方法
在方法的最后,它會執(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)類,ConfigurableServletWebServerFactory
是ServletWebServerFactory
類的子類,提供了很多方法供我們使用
代碼樣例如下
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的體系結(jié)構(gòu),Java幾乎成為了“開源”的代名詞。第三方開源軟件和框架。如Tomcat、Struts,MyBatis,Spring等,下面我們來看看文章具體的內(nèi)容介紹吧2022-01-01從Hello?World開始理解GraphQL背后處理及執(zhí)行過程
這篇文章主要為大家介紹了從Hello?World開始理解GraphQL背后處理過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08SpringBoot+MyBatisPlus中樂觀鎖的實現(xiàn)示例
樂觀鎖是一種用于解決并發(fā)沖突的機制,在數(shù)據(jù)庫中用于保護數(shù)據(jù)的一致性,本文主要介紹了SpringBoot+MyBatisPlus中樂觀鎖的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2023-08-08Java通過導(dǎo)出超大Excel文件解決內(nèi)存溢出問題
導(dǎo)出excel是咱Java開發(fā)的必備技能,下面這篇文章主要給大家介紹了關(guān)于Java通過導(dǎo)出超大Excel文件解決內(nèi)存溢出問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2021-09-09Java 實戰(zhàn)項目之小說在線閱讀系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實現(xiàn)前臺閱讀后臺管理的小說在線閱讀系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11