SpringBoot嵌入式Servlet容器與定制化組件超詳細(xì)講解
嵌入式Servlet容器
在Spring Boot中,默認(rèn)支持的web容器有 Tomcat, Jetty, 和 Undertow
1、原理分析
那么這些web容器是怎么注入的呢?我們一起來分析一下
當(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)建對應(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)用對應(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容器,可以通過哪些途徑呢?
- 通過分析
ServletWebServerFactoryAutoConfiguration綁定了ServerProperties配置類可知,我們想要修改容器的配置,只需要修改配置文件中對應(yīng)的server.xxx配置項(xiàng)即可 - 創(chuàng)建一個(gè)配置類,通過@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é)合之前的原理分析過程可知,我們分析一個(gè)組件的過程可以概括為:
導(dǎo)入對應(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接口,重寫對應(yīng)方法即可定制化web功能,或者使用@Bean給容器中再擴(kuò)展一些組件(這條是最重要的)

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

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

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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?invokeBeanFactoryPostProcessors方法刨析源碼
invokeBeanFactoryPostProcessors該方法會(huì)實(shí)例化所有BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的實(shí)例并且執(zhí)行postProcessBeanFactory與postProcessBeanDefinitionRegistry方法2023-01-01
java動(dòng)態(tài)目錄樹的實(shí)現(xiàn)示例
在開發(fā)過程中,常常需要對目錄結(jié)構(gòu)進(jìn)行操作和展示,本文主要介紹了java動(dòng)態(tài)目錄樹的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03
Spring Boot中l(wèi)ombok的安裝與使用詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot中l(wèi)ombok安裝與使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解
今天小編就為大家分享一篇關(guān)于Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03
Java 根據(jù)url下載網(wǎng)絡(luò)資源
這篇文章主要介紹了Java 根據(jù)url下載網(wǎng)絡(luò)資源的示例代碼,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-11-11

