SpringBoot嵌入式Servlet容器與定制化組件超詳細(xì)講解
嵌入式Servlet容器
在Spring Boot中,默認(rèn)支持的web容器有 Tomcat, Jetty, 和 Undertow
1、原理分析
那么這些web容器是怎么注入的呢?我們一起來(lái)分析一下
當(dāng)SpringBoot應(yīng)用啟動(dòng)發(fā)現(xiàn)當(dāng)前是Web應(yīng)用,它會(huì)創(chuàng)建一個(gè)web版的ioc容器ServletWebServerApplicationContext
這個(gè)類下面有一個(gè)createWebServer()方法,當(dāng)執(zhí)行關(guān)鍵代碼ServletWebServerFactory factory = this.getWebServerFactory();時(shí),它會(huì)在系統(tǒng)啟動(dòng)的時(shí)候?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());
// 這里會(huì)去調(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底層默認(rèn)有很多的WebServer工廠:TomcatServletWebServerFactory,,JettyServletWebServerFactory和 UndertowServletWebServerFactory

那么究竟返回哪一個(gè)工廠呢?
我們需要分析一下底層的自動(dòng)配置類,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() {
}
...它引入了一個(gè)配置類ServletWebServerFactoryConfiguration,這個(gè)類里面會(huì)根據(jù)動(dòng)態(tài)判斷系統(tǒng)中到底導(dǎo)入了那個(gè)Web服務(wù)器的包,然后去創(chuàng)建對(duì)應(yīng)的web容器工廠,spring-boot-starter-web這個(gè)依賴默認(rèn)導(dǎo)入tomcat,所以我們系統(tǒng)會(huì)創(chuàng)建TomcatServletWebServerFactory,由這個(gè)工廠創(chuàng)建tomcat容器并啟動(dòng)

一旦我們獲取到web Server的工廠類,createWebServer()方法就會(huì)去調(diào)用this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
根據(jù)斷點(diǎn)一直深入,我們可以發(fā)現(xiàn),Tomcat, Jetty, 和 Undertow的工廠類最后都會(huì)去調(diào)用getWebServer()方法,設(shè)置了鏈接參數(shù),例如TomcatServletWebServerFactory的getWebServer()方法
在方法的最后,它會(huì)執(zhí)行return this.getTomcatWebServer(tomcat);,跟著斷點(diǎn)深入,我們發(fā)現(xiàn)它會(huì)去調(diào)用對(duì)應(yīng)web容器類的構(gòu)造方法,如TomcatWebServer的構(gòu)造方法,啟動(dòng)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---會(huì)調(diào)用this.tomcat.start();啟動(dòng)容器
this.initialize();
}

2、Servlet容器切換
Spring Boot默認(rèn)使用的是tomcat容器,那如果我們想要使用Undertow應(yīng)該如何切換呢
只需要修改pom文件即可,排除web啟動(dòng)器中tomcat相關(guān)的依賴
然后導(dǎo)入U(xiǎn)ndertow相關(guān)啟動(dòng)器
<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容器配置
如果想要自己定義一個(gè)Servlet容器,可以通過(guò)哪些途徑呢?
- 通過(guò)分析
ServletWebServerFactoryAutoConfiguration綁定了ServerProperties配置類可知,我們想要修改容器的配置,只需要修改配置文件中對(duì)應(yīng)的server.xxx配置項(xiàng)即可 - 創(chuàng)建一個(gè)配置類,通過(guò)@Configuration+@Bean的方式,向容器中注入一個(gè)
ConfigurableServletWebServerFactory類的實(shí)現(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;
}
}自定義一個(gè)ServletWebServerFactoryCustomizer類,它的下面有一個(gè)customize()方法,能把配置文件的值和ServletWebServerFactory 進(jìn)行綁定

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

Spring中有很多xxxxxCustomizer,它的作用是定制化器,可以改變xxxx的默認(rèn)規(guī)則
定制化組件
結(jié)合之前的原理分析過(guò)程可知,我們分析一個(gè)組件的過(guò)程可以概括為:
導(dǎo)入對(duì)應(yīng)啟動(dòng)器xxx-starter---->分析xxxAutoConfiguration---->導(dǎo)入xxx組件---->綁定xxxProperties配置類----->綁定配置項(xiàng)
那么如果我們要定制化組件,例如自定義參數(shù)解析器或者應(yīng)用啟動(dòng)端口等,可以怎么做呢?
- 修改配置文件 server.xxx
- 參考上面編寫一個(gè)xxxxxCustomizer類
- 編寫自定義的配置類xxxConfiguration:使用@Configuration + @Bean替換、增加容器中默認(rèn)組件
- 如果是Web應(yīng)用,編寫一個(gè)配置類實(shí)現(xiàn)
WebMvcConfigurer接口,重寫對(duì)應(yīng)方法即可定制化web功能,或者使用@Bean給容器中再擴(kuò)展一些組件(這條是最重要的)

注意:@EnableWebMvc + 實(shí)現(xiàn)WebMvcConfigurer接口:配置類中定義的@Bean可以全面接管SpringMVC,所有規(guī)則全部自己重新配置
原理:
WebMvcAutoConfiguration類是SpringMVC的自動(dòng)配置功能類。配置了靜態(tài)資源、歡迎頁(yè)…- 一旦使用
@EnableWebMvc會(huì),@Import(DelegatingWebMvcConfiguration.class)

DelegatingWebMvcConfiguration類的作用是:只保證SpringMVC最基本的使用
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport表明它是WebMvcConfigurationSupport的子類- 它會(huì)把所有系統(tǒng)中的 WebMvcConfigurer的實(shí)現(xiàn)類拿過(guò)來(lái),所有功能的定制都是這些WebMvcConfigurer的實(shí)現(xiàn)類合起來(lái)一起生效

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

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

到此這篇關(guān)于SpringBoot嵌入式Servlet容器與定制化組件超詳細(xì)講解的文章就介紹到這了,更多相關(guān)SpringBoot Servlet容器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java基礎(chǔ)-Java的體系結(jié)構(gòu)
這篇文章主要介紹了Java的體系結(jié)構(gòu),Java幾乎成為了“開源”的代名詞。第三方開源軟件和框架。如Tomcat、Struts,MyBatis,Spring等,下面我們來(lái)看看文章具體的內(nèi)容介紹吧2022-01-01
從Hello?World開始理解GraphQL背后處理及執(zhí)行過(guò)程
這篇文章主要為大家介紹了從Hello?World開始理解GraphQL背后處理過(guò)程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
SpringBoot中使用@Async注解失效場(chǎng)景及說(shuō)明
在Spring?Boot中,@Async注解就像一把刀,能幫你輕松處理那些耗時(shí)的任務(wù),讓主線程可以繼續(xù)忙別的事兒,不過(guò),跟所有強(qiáng)大的工具一樣,用不好它也可能出岔子,為了避免這些坑,咱們得深入了解下@Async注解,接下來(lái),咱們就來(lái)聊聊7種常見的@Async失效情況,需要的朋友可以參考下2024-07-07
SpringBoot+MyBatisPlus中樂觀鎖的實(shí)現(xiàn)示例
樂觀鎖是一種用于解決并發(fā)沖突的機(jī)制,在數(shù)據(jù)庫(kù)中用于保護(hù)數(shù)據(jù)的一致性,本文主要介紹了SpringBoot+MyBatisPlus中樂觀鎖的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
Java基于Semaphore構(gòu)建阻塞對(duì)象池
這篇文章主要介紹了Java基于Semaphore構(gòu)建阻塞對(duì)象池,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Java通過(guò)導(dǎo)出超大Excel文件解決內(nèi)存溢出問題
導(dǎo)出excel是咱Java開發(fā)的必備技能,下面這篇文章主要給大家介紹了關(guān)于Java通過(guò)導(dǎo)出超大Excel文件解決內(nèi)存溢出問題的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09
Java 實(shí)戰(zhàn)項(xiàng)目之小說(shuō)在線閱讀系統(tǒng)的實(shí)現(xiàn)流程
讀萬(wàn)卷書不如行萬(wàn)里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實(shí)現(xiàn)前臺(tái)閱讀后臺(tái)管理的小說(shuō)在線閱讀系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2021-11-11

