SpringBoot啟動(dòng)嵌入式Tomcat的實(shí)現(xiàn)步驟
Spring Boot在內(nèi)部啟動(dòng)了一個(gè)嵌入式Web容器。
Tomcat是組件化設(shè)計(jì),所以就是啟動(dòng)這些組件。
Tomcat獨(dú)立部署模式是通過startup腳本啟動(dòng),Tomcat中的Bootstrap和Catalina會(huì)負(fù)責(zé)初始化類加載器,并解析server.xml和啟動(dòng)這些組件。
內(nèi)嵌模式,Bootstrap和Catalina的工作由Spring Boot代勞,Spring Boot調(diào)用Tomcat API啟動(dòng)這些組件。
Spring Boot中Web容器相關(guān)接口
WebServer
為支持各種Web容器,Spring Boot抽象出嵌入式Web容器,定義WebServer接口:

Web容器比如Tomcat、Jetty去實(shí)現(xiàn)該接口

ServletWebServerFactory
創(chuàng)建Web容器,返回的就是上面提到的WebServer。
public interface ServletWebServerFactory {
WebServer getWebServer(ServletContextInitializer... initializers);
}
ServletContextInitializer入?yún)⒈硎維ervletContext的初始化器,用于ServletContext中的一些配置:
public interface ServletContextInitializer {
void onStartup(ServletContext servletContext) throws ServletException;
}
getWebServer會(huì)調(diào)用ServletContextInitializer#onStartup,即若想在Servlet容器啟動(dòng)時(shí)做一些事情,比如注冊自己的Servlet,可以實(shí)現(xiàn)一個(gè)ServletContextInitializer,在Web容器啟動(dòng)時(shí),Spring Boot會(huì)把所有實(shí)現(xiàn)ServletContextInitializer接口的類收集起來,統(tǒng)一調(diào)其onStartup。
WebServerFactoryCustomizerBeanPostProcessor
一個(gè)BeanPostProcessor,為定制化嵌入式Web容器,在postProcessBeforeInitialization過程中去尋找Spring容器中WebServerFactoryCustomizer類型的Bean,并依次調(diào)用WebServerFactoryCustomizer接口的customize方法做一些定制化。
public interface WebServerFactoryCustomizer<T extends WebServerFactory> {
void customize(T factory);
}
創(chuàng)建、啟動(dòng)嵌入式Web容器
Spring的ApplicationContext,其抽象實(shí)現(xiàn)類AbstractApplicationContext#refresh

用來新建或刷新一個(gè)ApplicationContext,在refresh中會(huì)調(diào)用onRefresh,AbstractApplicationContext的子類可以重寫onRefresh實(shí)現(xiàn)Context刷新邏輯。
因此重寫 ServletWebServerApplicationContext#onRefresh 創(chuàng)建嵌入式Web容器:

重寫onRefresh方法,調(diào)用createWebServer創(chuàng)建和啟動(dòng)Tomcat。
createWebServer
private void createWebServer() {
// WebServer是Spring Boot抽象出來的接口,具體實(shí)現(xiàn)類就是不同Web容器
WebServer webServer = this.webServer;
ServletContext servletContext = this.getServletContext();
// 若Web容器尚未創(chuàng)建
if (webServer == null && servletContext == null) {
// 通過Web容器工廠創(chuàng)建
ServletWebServerFactory factory = this.getWebServerFactory();
// 傳入一個(gè)"SelfInitializer"
this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
} else if (servletContext != null) {
try {
this.getSelfInitializer().onStartup(servletContext);
} catch (ServletException var4) {
...
}
}
this.initPropertySources();
}
getWebServer
以Tomcat為例,主要調(diào)用Tomcat的API去創(chuàng)建各種組件:
public WebServer getWebServer(ServletContextInitializer... initializers) {
// 1.實(shí)例化一個(gè)Tomcat【Server組件】
Tomcat tomcat = new Tomcat();
// 2. 創(chuàng)建一個(gè)臨時(shí)目錄
File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
// 3.初始化各種組件
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
this.customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
this.configureEngine(tomcat.getEngine());
// 4. 創(chuàng)建定制版的"Context"組件
this.prepareContext(tomcat.getHost(), initializers);
return this.getTomcatWebServer(tomcat);
}
prepareContext的Context指Tomcat的Context組件,為控制Context組件行為,Spring Boot自定義了TomcatEmbeddedContext類,繼承Tomcat的StandardContext:

注冊Servlet
有@RestController,為什么還要自己去注冊Servlet給Tomcat?
可能有些場景需要注冊你自己寫的一個(gè)Servlet提供輔助功能,與主程序分開。
Sprong Boot 不注冊Servlet 給Tomcat 直接用 @Controller 就能實(shí)現(xiàn)Servlet功能是為啥呢?
因?yàn)镾prong Boot默認(rèn)給我們注冊了DispatcherSetvlet。
Servlet注解
在Spring Boot啟動(dòng)類上加上 @ServletComponentScan 注解后,使用@WebServlet、@WebFilter、@WebListener標(biāo)記的Servlet、Filter、Listener就可以自動(dòng)注冊到Servlet容器。


在Web應(yīng)用的入口類上加上@ServletComponentScan,并且在Servlet類上加上@WebServlet,這樣Spring Boot會(huì)負(fù)責(zé)將Servlet注冊到內(nèi)嵌的Tomcat中。
ServletRegistrationBean
Spring Boot提供了
- ServletRegistrationBean
- FilterRegistrationBean
- ServletListenerRegistrationBean
分別用來注冊Servlet、Filter、Listener。
假如要注冊一個(gè)Servlet:

返回一個(gè)ServletRegistrationBean,并將它當(dāng)作Bean注冊到Spring,因此你需要把這段代碼放到Spring Boot自動(dòng)掃描的目錄中,或者放到**@Configuration**標(biāo)識(shí)的類中。
Spring會(huì)把這種類型的Bean收集起來,根據(jù)Bean里的定義向Tomcat注冊Servlet。
動(dòng)態(tài)注冊
可以創(chuàng)建一個(gè)類去實(shí)現(xiàn)ServletContextInitializer接口,并把它注冊為一個(gè)Bean,Spring Boot會(huì)負(fù)責(zé)調(diào)用這個(gè)接口的onStartup。
實(shí)現(xiàn)ServletContextInitializer接口的類會(huì)被spring管理,而不是被Servlet容器管理。
@Component
public class MyServletRegister implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// Servlet 3.0規(guī)范新的API
ServletRegistration myServlet = servletContext
.addServlet("HelloServlet", HelloServlet.class);
myServlet.addMapping("/hello");
myServlet.setInitParameter("name", "Hello Servlet");
}
}
ServletRegistrationBean也是通過ServletContextInitializer實(shí)現(xiàn)的,它實(shí)現(xiàn)了ServletContextInitializer接口。
注意到onStartup方法的參數(shù)是我們熟悉的ServletContext,可以通過調(diào)用它的addServlet方法來動(dòng)態(tài)注冊新的Servlet,這是Servlet 3.0以后才有的功能。
通過 ServletContextInitializer 接口可以向 Web 容器注冊 Servlet,實(shí)現(xiàn) ServletContextInitializer 接口的Bean被speing管理,但是在什么時(shí)機(jī)觸發(fā)其onStartup()方法的呢?
通過 Tomcat 中的 ServletContainerInitializer 接口實(shí)現(xiàn)者,如TomcatStarter,創(chuàng)建tomcat時(shí)設(shè)置了該類,在tomcat啟動(dòng)時(shí)會(huì)觸發(fā)ServletContainerInitializer實(shí)現(xiàn)者的onStartup()方法,在這個(gè)方法中觸發(fā)ServletContextInitializer接口的onStartup()方法,如注冊DispatcherServlet。
DispatcherServletRegistrationBean實(shí)現(xiàn)了ServletContextInitializer接口,它的作用就是向Tomcat注冊DispatcherServlet,那它是在什么時(shí)候、如何被使用的呢?
prepareContext方法調(diào)用了另一個(gè)私有方法configureContext,這個(gè)方法就包括了往Tomcat的Context添加ServletContainerInitializer對象:
context.addServletContainerInitializer(starter, NO_CLASSES);
其中有DispatcherServletRegistrationBean。
定制Web容器
如何在Spring Boot中定制Web容器。在Spring Boot 2.0中可通過如下方式:
ConfigurableServletWebServerFactory
通用的Web容器工廠,定制Web容器通用參數(shù):
@Component
public class MyGeneralCustomizer implements
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
public void customize(ConfigurableServletWebServerFactory factory) {
factory.setPort(8081);
factory.setContextPath("/hello");
}
}
TomcatServletWebServerFactory
通過特定Web容器工廠進(jìn)一步定制。
給Tomcat增加一個(gè)Valve,這個(gè)Valve的功能是向請求頭里添加traceid,用于分布式追蹤。
class TraceValve extends ValveBase {
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
request.getCoyoteRequest().getMimeHeaders().
addValue("traceid").setString("1234xxxxabcd");
Valve next = getNext();
if (null == next) {
return;
}
next.invoke(request, response);
}
}
跟方式一類似,再添加一個(gè)定制器:
@Component
public class MyTomcatCustomizer implements
WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
@Override
public void customize(TomcatServletWebServerFactory factory) {
factory.setPort(8081);
factory.setContextPath("/hello");
factory.addEngineValves(new TraceValve() );
}
}
到此這篇關(guān)于SpringBoot啟動(dòng)嵌入式Tomcat的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)SpringBoot啟動(dòng)嵌入式Tomcat內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
聊聊Spring MVC JSON數(shù)據(jù)交互的問題
我們在開發(fā)中后端經(jīng)常需要接受來自于前端傳遞的Json字符串?dāng)?shù)據(jù),怎么把Json字符串轉(zhuǎn)換為Java對象呢?下面小編給大家?guī)砹薙pring MVC JSON數(shù)據(jù)交互的問題,感興趣的朋友一起看看吧2021-10-10
spring多數(shù)據(jù)源配置實(shí)現(xiàn)方法實(shí)例分析
這篇文章主要介紹了spring多數(shù)據(jù)源配置實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了spring多數(shù)據(jù)源配置相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下2019-12-12
java ant 配置及構(gòu)建項(xiàng)目圖文教程
以下是對java ant配置及構(gòu)建項(xiàng)目進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下2013-08-08
java啟動(dòng)jar包修改JVM默認(rèn)內(nèi)存問題
這篇文章主要介紹了java啟動(dòng)jar包修改JVM默認(rèn)內(nèi)存問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
springSecurity實(shí)現(xiàn)簡單的登錄功能
這篇文章主要為大家詳細(xì)介紹了springSecurity實(shí)現(xiàn)簡單的登錄功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09
mybatis 解決從列名到屬性名的自動(dòng)映射失敗問題
這篇文章主要介紹了mybatis 解決從列名到屬性名的自動(dòng)映射失敗問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06

