本文結(jié)論
- 源碼基于spring boot2.6.6
- 項目的pom.xml中存在spring-boot-starter-web的時候,在項目啟動時候就會自動啟動一個Tomcat 。
- 自動配置類ServletWebServerFactoryAutoConfiguration找到系統(tǒng)中的所有web容器 。我們以tomcat為主 。
- 構(gòu)建TomcatServletWebServerFactory的bean 。
- SpringBoot的啟動過程中,會調(diào)用核心的refresh方法,內(nèi)部會執(zhí)行onRefresh()方法,onRefresh()方法是一個模板方法,他會執(zhí)行會執(zhí)行子類ServletWebServerApplicationContext的onRefresh()方法 。
- onRefresh()方法中調(diào)用getWebServer啟動web容器 。
- 在spring-boot-starter-web這個starter中,其實內(nèi)部間接的引入了spring-boot-starter-tomcat這個starter,這個spring-boot-starter-tomcat又引入了tomcat-embed-core依賴,所以只要我們項目中依賴了spring-boot-starter-web就相當于依賴了Tomcat 。

文章插圖

文章插圖
自動配置類:ServletWebServerFactoryAutoConfiguration
- 在spring-boot-autoconfigure-2.6.6.jar這個包中的spring.factories文件內(nèi),配置了大量的自動配置類,其中就包括自動配置tomcat的自動配置類:ServletWebServerFactoryAutoConfiguration

文章插圖
自動配置類的代碼如下// full模式@Configuration(proxyBeanMethods = false)// 配置類解析順序@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)// 條件注解:表示項目依賴中要有ServletRequest類(server api)@ConditionalOnClass(ServletRequest.class)// 表示項目應用類型得是SpringMVC(在啟動過程中獲取的SpringBoot應用類型)@ConditionalOnWebApplication(type = Type.SERVLET)// 讀取server下的配置文件@EnableConfigurationProperties(ServerProperties.class)// import具體的加載配置的類和具體web實現(xiàn)容器@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,ServletWebServerFactoryConfiguration.EmbeddedJetty.class,ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })public class ServletWebServerFactoryAutoConfiguration { ......}
- ServletRequest是存在于tomcat-embed-core-9.0.60.jar中的的一個類,所以@ConditionalOnClass(ServletRequest.clas s)會滿足 。
- spring-boot-starter-web中,間接的引入了spring-web、spring-webmvc等依賴,所以@ConditionalOnWebApplication(type = Type.SERVLET)條件滿足 。
- 上面的倆個條件都滿足,所以spring回去解析這個配置類,在解析過程中會發(fā)現(xiàn)他import了三個類!我們重點關(guān)注EmbeddedTomcat 。其他倆個的內(nèi)部條件注解不滿足!
經(jīng)驗總結(jié)擴展閱讀
- time使用 研一小白入坑Go
- Spring Boot 配置 jar 包外面的 Properties 配置文件
- 【C++】從零開始的CS:GO逆向分析3——寫出一個透視
- 適合隔夜帶飯的菜譜
- 雨傘放行李箱托運會被開箱嗎
- 臺灣的美稱
- 夏天乳鴿煲湯用什么材料
- 連州特產(chǎn)有哪些
- 華縣大地震是哪一年
- 芋圓材料
