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)該接口
創(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í)做一些事情,比如注冊(cè)自己的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。
createWebServerprivate 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:
有@RestController,為什么還要自己去注冊(cè)Servlet給Tomcat?可能有些場(chǎng)景需要注冊(cè)你自己寫的一個(gè)Servlet提供輔助功能,與主程序分開。
Sprong Boot 不注冊(cè)Servlet 給Tomcat 直接用 @Controller 就能實(shí)現(xiàn)Servlet功能是為啥呢?因?yàn)镾prong Boot默認(rèn)給我們注冊(cè)了DispatcherSetvlet。
Servlet注解在Spring Boot啟動(dòng)類上加上 @ServletComponentScan 注解后,使用@WebServlet、@WebFilter、@WebListener標(biāo)記的Servlet、Filter、Listener就可以自動(dòng)注冊(cè)到Servlet容器。
在Web應(yīng)用的入口類上加上@ServletComponentScan,并且在Servlet類上加上@WebServlet,這樣Spring Boot會(huì)負(fù)責(zé)將Servlet注冊(cè)到內(nèi)嵌的Tomcat中。
ServletRegistrationBeanSpring Boot提供了
ServletRegistrationBean FilterRegistrationBean ServletListenerRegistrationBean分別用來注冊(cè)Servlet、Filter、Listener。假如要注冊(cè)一個(gè)Servlet:
返回一個(gè)ServletRegistrationBean,并將它當(dāng)作Bean注冊(cè)到Spring,因此你需要把這段代碼放到Spring Boot自動(dòng)掃描的目錄中,或者放到**@Configuration**標(biāo)識(shí)的類中。Spring會(huì)把這種類型的Bean收集起來,根據(jù)Bean里的定義向Tomcat注冊(cè)Servlet。
動(dòng)態(tài)注冊(cè)可以創(chuàng)建一個(gè)類去實(shí)現(xiàn)ServletContextInitializer接口,并把它注冊(cè)為一個(gè)Bean,Spring Boot會(huì)負(fù)責(zé)調(diào)用這個(gè)接口的onStartup。
實(shí)現(xiàn)ServletContextInitializer接口的類會(huì)被spring管理,而不是被Servlet容器管理。
@Componentpublic class MyServletRegister implements ServletContextInitializer { @Override public void onStartup(ServletContext servletContext) { // Servlet 3.0規(guī)范新的APIServletRegistration 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)注冊(cè)新的Servlet,這是Servlet 3.0以后才有的功能。
通過 ServletContextInitializer 接口可以向 Web 容器注冊(cè) 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()方法,如注冊(cè)DispatcherServlet。
DispatcherServletRegistrationBean實(shí)現(xiàn)了ServletContextInitializer接口,它的作用就是向Tomcat注冊(cè)DispatcherServlet,那它是在什么時(shí)候、如何被使用的呢?prepareContext方法調(diào)用了另一個(gè)私有方法configureContext,這個(gè)方法就包括了往Tomcat的Context添加ServletContainerInitializer對(duì)象:
context.addServletContainerInitializer(starter, NO_CLASSES);
其中有DispatcherServletRegistrationBean。
定制Web容器如何在Spring Boot中定制Web容器。在Spring Boot 2.0中可通過如下方式:
ConfigurableServletWebServerFactory通用的Web容器工廠,定制Web容器通用參數(shù):
@Componentpublic 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的功能是向請(qǐng)求頭里添加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è)定制器:
@Componentpublic class MyTomcatCustomizer implementsWebServerFactoryCustomizer<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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python GUI庫圖形界面開發(fā)之PyQt5動(dòng)態(tài)(可拖動(dòng)控件大小)布局控件QSplitter詳細(xì)使用方法與實(shí)例2. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)3. XML 非法字符(轉(zhuǎn)義字符)4. ASP 處理JSON數(shù)據(jù)的實(shí)現(xiàn)代碼5. js開發(fā)中的頁面、屏幕、瀏覽器的位置原理(高度寬度)說明講解(附圖)6. CSS清除浮動(dòng)方法匯總7. 不要在HTML中濫用div8. vue跳轉(zhuǎn)頁面常用的幾種方法匯總9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. XML入門的常見問題(三)
