web.xml?SpringBoot打包可執(zhí)行Jar運(yùn)行SpringMVC加載流程
部署到webapps目錄啟動(dòng)
本文使用的Spring版本為Spring6,SpringBoot版本為3,JDK為17,可能會(huì)和之前有細(xì)微不同,但整體流程差不太大。
如果部署應(yīng)用到tomcat webapps目錄下面啟動(dòng),則需要在項(xiàng)目中配置web.xml文件
web.xml文件
配置Spring應(yīng)用上下文
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/application-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
context-param
context-param標(biāo)簽是用于在Web應(yīng)用程序的上下文范圍內(nèi)設(shè)置初始化參數(shù)。這些參數(shù)可以在整個(gè)Web應(yīng)用程序中使用,并且可以通過(guò)ServletContext對(duì)象的getInitParameter()方法獲取。
ContextLoaderListener
ContextLoaderListener實(shí)現(xiàn)了ServletContextListener接口,這個(gè)接口是tomcat留給應(yīng)用程序初始化上下文環(huán)境的接口,用于在Web應(yīng)用程序啟動(dòng)時(shí)加載ApplicationContext。
ServletContextListener有兩個(gè)默認(rèn)方法
// 在所有的servlet和filter初始化之前被調(diào)用 default public void contextInitialized(ServletContextEvent sce) { } // 在所有的servlet和filter銷(xiāo)毀之后被調(diào)用 default public void contextDestroyed(ServletContextEvent sce) { }
ContextLoaderListener還繼承了ContextLoader類(lèi),所有的context操作都在此類(lèi)進(jìn)行。
ContextLoaderListener實(shí)現(xiàn)contextInitialized方法,然后調(diào)用父類(lèi)ContextLoader的initWebApplicationContext方法,把ServletContext傳進(jìn)去。
@Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); }
初始化Spring Context。
initWebApplicationContext方法關(guān)鍵代碼
... if (this.context == null) { // 創(chuàng)建ApplicationContext this.context = createWebApplicationContext(servletContext); } ... // 刷新ApplicationContext configureAndRefreshWebApplicationContext(cwac, servletContext); ... // 將當(dāng)前ApplicationContext添加到ServletContext的屬性中,后面有用再說(shuō) // String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ...
創(chuàng)建ApplicationContext
在createWebApplicationContext方法中,先調(diào)用determineContextClass方法確定使用哪個(gè)ApplicationContext,找到之后,實(shí)例化。
determineContextClass這個(gè)方法,主要是確定使用的ApplicationContext,首先從web.xml中加載,如果用戶(hù)有定義,直接使用用戶(hù)自定義的。
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
web.xml中配置如下,
<context-param> <param-name>contextClass</param-name> <param-value>com.xxx.XxxContext</param-value> </context-param>
如果沒(méi)有配置,則使用Spring默認(rèn)的XmlWebApplicationContext類(lèi)。
這個(gè)類(lèi)在ContextLoader同路徑包下面的ContextLoader.properties文件中定義。
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
配置和刷新ApplicationContext
configureAndRefreshWebApplicationContext關(guān)鍵代碼
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,ServletContext sc) { // ... // 獲取web.xml中配置的contextConfigLocation參數(shù) String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (configLocationParam != null) { wac.setConfigLocation(configLocationParam); } // ... // 刷新上下文 wac.refresh(); }
至此Tomcat已經(jīng)啟動(dòng)Spring環(huán)境了,后續(xù)就是Spring的初始化流程,這里不再敘述。
初始化DispatcherServlet
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
此處的contextConfigLocation屬于DispatcherServlet的父類(lèi)FrameworkServlet,主要用來(lái)加載SpringMVC相關(guān)的配置,示例如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 掃描控制器和其他組件 --> <context:component-scan base-package="com.example.controller" /> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 啟用Spring MVC注解支持 --> <mvc:annotation-driven /> </beans>
DispatcherServlet類(lèi)圖
可以看到DispatcherServlet實(shí)現(xiàn)了Servlet接口,Servlet接口中有init方法,SpringMVC的配置就是在初始化的時(shí)候被加載的。
關(guān)鍵代碼在HttpServletBean.init()和FrameworkServlet.initServletBean()方法中。
HttpServletBean.init()
public final void init() throws ServletException { // Set bean properties from init parameters. PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties); if (!pvs.isEmpty()) { try { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext()); bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment())); initBeanWrapper(bw); bw.setPropertyValues(pvs, true); } catch (BeansException ex) { if (logger.isErrorEnabled()) { logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex); } throw ex; } } // Let subclasses do whatever initialization they like. initServletBean(); }
FrameworkServlet.initServletBean()
protected final void initServletBean() throws ServletException { ... // 在這里初始化ApplicationContext this.webApplicationContext = initWebApplicationContext(); // 初始化servlet initFrameworkServlet(); }
FrameworkServlet.initWebApplicationContext()
protected WebApplicationContext initWebApplicationContext() { // 此處獲取根容器,就是Spring初始化的XmlWebApplicationContext, // 在上面把它添加到了ServletContext的屬性中,標(biāo)記根容器,這里把它獲取出來(lái) // String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; // servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext wac = null; // 此時(shí)webApplicationContext還是null,因?yàn)镈ispatchServlet是被tomcat創(chuàng)建的,需要無(wú)參構(gòu)造器 // 構(gòu)造器中沒(méi)有設(shè)置webApplicationContext的代碼,所以此時(shí)webApplicationContext還是null // 注意:在SpringBoot使用嵌入式Tomcat時(shí),這個(gè)webApplicationContext不為null,因?yàn)镕rameworkServlet還 // 實(shí)現(xiàn)了ApplicationContextAware接口,所以當(dāng)SpringBoot的上下文準(zhǔn)備好之后,會(huì)回調(diào)setApplicationContext方法 // 注入ApplicationContext,后面在細(xì)說(shuō) if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext cwac && !cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> set // the root application context (if any; may be null) as the parent cwac.setParent(rootContext); } configureAndRefreshWebApplicationContext(cwac); } } if (wac == null) { // No context instance was injected at construction time -> see if one // has been registered in the servlet context. If one exists, it is assumed // that the parent context (if any) has already been set and that the // user has performed any initialization such as setting the context id // 此處主要是獲取web.xml配置的WebApplicationContext // 可以通過(guò)設(shè)置參數(shù)contextAttribute來(lái)設(shè)置加載SpringMVC的ApplicationContext // 比如下面這樣。除非項(xiàng)目中有多個(gè)WebApplicationContext,需要使用其他WebApplicationContext才會(huì)用到 // 一般都是null // <context-param> // <param-name>contextAttribute</param-name> // <param-value>myWebApplicationContext</param-value> // </context-param> wac = findWebApplicationContext(); } if (wac == null) { // 現(xiàn)在進(jìn)入到創(chuàng)建SpringMVC的ApplicationContext流程 // 也就是加載contextConfigLocation定義的xml文件 // No context instance is defined for this servlet -> create a local one wac = createWebApplicationContext(rootContext); } if (!this.refreshEventReceived) { // Either the context is not a ConfigurableApplicationContext with refresh // support or the context injected at construction time had already been // refreshed -> trigger initial onRefresh manually here. synchronized (this.onRefreshMonitor) { // 初始化策略對(duì)象 // 比如:HandlerMapping,HandlerAdapter,ViewResolver等等 onRefresh(wac); } } if (this.publishContext) { // Publish the context as a servlet context attribute. String attrName = getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); } return wac; }
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) { // SpringMVC所使用的contextClass,可以在<servlet>標(biāo)簽下設(shè)置 // <init-param> // <param-name>contextClass</param-name> // <param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value> // </init-param> // 默認(rèn)為XmlWebApplicationContext Class<?> contextClass = getContextClass(); if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException( "Fatal initialization error in servlet with name '" + getServletName() + "': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext"); } // 實(shí)例化ApplicationContext ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); // 設(shè)置環(huán)境參數(shù) wac.setEnvironment(getEnvironment()); // 設(shè)置父容器為Spring的ApplicationContext wac.setParent(parent); // 獲取SpringMVC的contextConfigLocation文件 String configLocation = getContextConfigLocation(); if (configLocation != null) { wac.setConfigLocation(configLocation); } // 配置并刷新ApplicationContext configureAndRefreshWebApplicationContext(wac); return wac; }
DispatchServlet初始化完成
為什么需要父子容器
父子容器的作用主要是劃分框架邊界和實(shí)現(xiàn)bean的復(fù)用。
- 在J2EE三層架構(gòu)中,在service層我們一般使用Spring框架,而在web層則有多種選擇,如Spring MVC、Struts等。為了讓web層能夠使用service層的bean,我們需要將service層的容器作為web層容器的父容器,這樣就可以實(shí)現(xiàn)框架的整合。
- 父子容器的作用在于,當(dāng)我們嘗試從子容器(Servlet WebApplicationContext)中獲取一個(gè)bean時(shí),如果找不到,則會(huì)委派給父容器(Root WebApplicationContext)進(jìn)行查找。這樣可以避免在多個(gè)子容器中重復(fù)定義相同的bean,提高了代碼的復(fù)用性和可維護(hù)性。
接收請(qǐng)求
請(qǐng)求先進(jìn)入doService,然后調(diào)用doDispatch進(jìn)行處理。
doDispatch關(guān)鍵代碼
... // 首先根據(jù)當(dāng)前請(qǐng)求HttpServletRequest,遍歷所有的HandlerMapping執(zhí)行handle方法,返回可用的HandlerExecutionChain對(duì)象。 mappedHandler = getHandler(processedRequest); // 然后根據(jù)handler獲取支持的適配器 HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // 執(zhí)行HandlerInterceptor.preHandle,在controller的方法被調(diào)用前執(zhí)行 if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; } // 執(zhí)行controller方法 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // 執(zhí)行HandlerInterceptor.postHandle,在controller的方法被調(diào)用后執(zhí)行 mappedHandler.applyPostHandle(processedRequest, response, mv); // 渲染結(jié)果到視圖 processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
- HandlerMapping是request與handler object之間的映射,它能根據(jù)request找到對(duì)應(yīng)的handler。handler object可以是任意類(lèi)型,比如@Controller注解的類(lèi),或者實(shí)現(xiàn)了Controller接口的類(lèi),或者實(shí)現(xiàn)了HttpRequestHandler接口的類(lèi)等。
- HandlerExecutionChain是handler執(zhí)行鏈,它包裝了handler object和一組HandlerInterceptor。HandlerInterceptor是攔截器,它可以在handler執(zhí)行前后進(jìn)行一些額外的操作,比如權(quán)限檢查,日志記錄等。
- HandlerAdapter是handler的適配器,它能處理不同類(lèi)型的handler object,并調(diào)用其對(duì)應(yīng)的方法,返回ModelAndView對(duì)象。HandlerAdapter可以根據(jù)handler object的類(lèi)型,進(jìn)行參數(shù)綁定,返回值處理等操作。
HandlerInterceptor使用
- 定義一個(gè)攔截器類(lèi),實(shí)現(xiàn)HandlerInterceptor接口或者繼承HandlerInterceptorAdapter類(lèi),重寫(xiě)preHandle,postHandle和afterCompletion三個(gè)方法。
- 在preHandle方法中,可以獲取請(qǐng)求和響應(yīng)對(duì)象,進(jìn)行預(yù)處理,比如檢查請(qǐng)求頭中的token,或者判斷請(qǐng)求的url是否有權(quán)限訪(fǎng)問(wèn)等。如果返回true,則繼續(xù)執(zhí)行后續(xù)的攔截器或者處理器;如果返回false,則中斷請(qǐng)求,不再執(zhí)行后續(xù)的攔截器或者處理器。
- 在postHandle方法中,可以獲取請(qǐng)求和響應(yīng)對(duì)象,以及處理器返回的ModelAndView對(duì)象,進(jìn)行后處理,比如修改模型數(shù)據(jù)或者視圖信息等。這個(gè)方法只有在preHandle返回true且處理器成功執(zhí)行后才會(huì)調(diào)用。
- 在afterCompletion方法中,可以獲取請(qǐng)求和響應(yīng)對(duì)象,以及處理器拋出的異常對(duì)象(如果有的話(huà)),進(jìn)行清理資源或者異常處理等。這個(gè)方法只有在preHandle返回true后才會(huì)調(diào)用,無(wú)論處理器是否成功執(zhí)行。
- 在SpringMVC的配置文件中,注冊(cè)攔截器類(lèi),并指定攔截的url模式??梢宰?cè)多個(gè)攔截器,并指定順序。攔截器會(huì)按照順序執(zhí)行preHandle方法,然后按照逆序執(zhí)行postHandle和afterCompletion方法。
HandlerInterceptor和Filter的區(qū)別
- HandlerInterceptor是基于Java反射機(jī)制的,而Filter是基于函數(shù)回調(diào)的。HandlerInterceptor可以利用Spring的AOP技術(shù),實(shí)現(xiàn)更靈活的攔截邏輯,而Filter只能在請(qǐng)求前后進(jìn)行簡(jiǎn)單的處理。
- HandlerInterceptor不依賴(lài)于Servlet容器,而Filter依賴(lài)于Servlet容器。HandlerInterceptor是SpringMVC框架提供的,可以在任何情況下使用,而Filter是Servlet規(guī)范的一部分,只能在Web應(yīng)用中使用。
- HandlerInterceptor的執(zhí)行由SpringMVC框架控制,而Filter的執(zhí)行由Servlet容器控制。HandlerInterceptor可以通過(guò)IoC容器來(lái)管理,可以注入其他的Bean,而Filter則需要在web.xml中配置,或者使用@WebFilter注解,并且需要@ServletComponentScan掃描。
- HandlerInterceptor只能攔截DispatcherServlet處理的請(qǐng)求,而Filter可以攔截任何請(qǐng)求。HandlerInterceptor只能對(duì)Controller方法進(jìn)行攔截,而Filter可以對(duì)靜態(tài)資源、JSP頁(yè)面等進(jìn)行攔截。
- HandlerInterceptor有三個(gè)方法:preHandle,postHandle和afterCompletion,分別在請(qǐng)求處理前后和視圖渲染前后執(zhí)行,而Filter只有一個(gè)方法:doFilter,在請(qǐng)求處理前后執(zhí)行。
處理controller返回結(jié)果
對(duì)于被controller方法,使用的適配器是RequestMappingHandlerAdapter,在handlerAdapter.handle方法執(zhí)行時(shí),會(huì)去執(zhí)行對(duì)應(yīng)的controller方法,處理controller方法返回的結(jié)果。
invocableMethod.invokeAndHandle(webRequest, mavContainer);
ServletInvocableHandlerMethod.invokeAndHandle
// 執(zhí)行controller方法 Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs); ... // 處理返回?cái)?shù)據(jù),會(huì)判斷是不是有@ResponseBody注解,如果有,會(huì)使用RequestResponseBodyMethodProcessor來(lái)處理返回值 // 然后會(huì)解析請(qǐng)求頭等等,判斷應(yīng)該返回什么類(lèi)型的數(shù)據(jù),然后使用對(duì)應(yīng)的HttpMessageConverter寫(xiě)入輸出流 this.returnValueHandlers.handleReturnValue( returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
SpringBoot Jar啟動(dòng)
SpringBoot使用嵌入式Servlet容器啟動(dòng)應(yīng)用,有Tomcat,Jetty,Undertow。
選擇Servlet容器
SpringBoot默認(rèn)使用Tomcat,可以在配置文件中看出。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
web模塊自動(dòng)引入了tomcat
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency>
如果不使用Tomcat可以排除,引入其他服務(wù)器。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 剔除Tomcat --> <exclusions> <exclusion> <artifactId>spring-boot-starter-tomcat</artifactId> <groupId>org.springframework.boot</groupId> </exclusion> </exclusions> </dependency> <!-- 使用jetty --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
如果沒(méi)有排除Tomcat,直接引入其他服務(wù)器,比如下面。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 沒(méi)有排除Tomcat --> </dependency> <!-- 引入jetty --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
如果項(xiàng)目中同時(shí)引入了Tomcat和其他服務(wù)器的依賴(lài),那么SpringBoot會(huì)按照以下順序來(lái)選擇啟動(dòng)的服務(wù)器。
Tomcat > Jetty > Undertow
也就是說(shuō),如果有Tomcat,就優(yōu)先使用Tomcat,如果沒(méi)有Tomcat,就看有沒(méi)有Jetty,如果有Jetty,就使用Jetty,以此類(lèi)推。這個(gè)順序是在SpringBoot的ServletWebServerFactoryConfiguration類(lèi)中定義的。
// 只展示必要代碼 class ServletWebServerFactoryConfiguration { // 當(dāng)Servlet、Tomcat、UpgradeProtocol類(lèi)在類(lèi)路徑存在時(shí) // 并且ServletWebServerFactory類(lèi)存在,則會(huì)創(chuàng)建tomcatServletWebServerFactory bean。 @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) static class EmbeddedTomcat { @Bean TomcatServletWebServerFactory tomcatServletWebServerFactory( ... 代碼省略 } } // 當(dāng)Servlet、Server、WebAppContext類(lèi)在類(lèi)路徑存在時(shí) // 并且ServletWebServerFactory類(lèi)型的Bean不存在時(shí),則會(huì)創(chuàng)建JettyServletWebServerFactory bean。 // ServletWebServerFactory是TomcatServletWebServerFactory、JettyServletWebServerFactory、 // UndertowServletWebServerFactory的父類(lèi) // 所以如果Tomcat被引入,上面的tomcatServletWebServerFactory就會(huì)被創(chuàng)建,這里的條件就不滿(mǎn)足,不會(huì)被創(chuàng)建。 @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) static class EmbeddedJetty { @Bean JettyServletWebServerFactory JettyServletWebServerFactory( ... 代碼省略 } } // 分析同上 @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) static class EmbeddedUndertow { @Bean UndertowServletWebServerFactory undertowServletWebServerFactory( ... 代碼省略 } }
下面繼續(xù)以Tomcat為例
Tomcat配置、啟動(dòng)
Tomcat是在Spring容器啟動(dòng)的時(shí)候啟動(dòng)的
SpringApplication.run
方法
首先創(chuàng)建一個(gè)ConfigurableApplicationContext對(duì)象,并調(diào)用其refresh()方法,這個(gè)對(duì)象一般是AnnotationConfigServletWebServerApplicationContext。
context = createApplicationContext(); -> refreshContext(context); -> refresh(context); -> applicationContext.refresh();
refresh()方法會(huì)調(diào)用其父類(lèi)ServletWebServerApplicationContext的refresh()方法,在父類(lèi)的refresh()中再次調(diào)用父類(lèi)AbstractApplicationContext的refresh()方法,主要在onRefresh階段,會(huì)進(jìn)行服務(wù)器的配置。
... refresh()代碼簡(jiǎn)略 // 這里會(huì)初始化Tomcat配置 onRefresh(); // 這里會(huì)啟動(dòng)Tomcat finishRefresh(); ...
回到ServletWebServerApplicationContext類(lèi)的onRefresh()方法,會(huì)調(diào)用createWebServer()方法,創(chuàng)建web服務(wù)器。
protected void onRefresh() { super.onRefresh(); try { // 創(chuàng)建服務(wù)器 createWebServer(); } catch (Throwable ex) { throw new ApplicationContextException("Unable to start web server", ex); } }
private void createWebServer() { ... 代碼簡(jiǎn)略 // 獲取工廠(chǎng)類(lèi),這里獲取的就是在配置類(lèi)中生效的那一個(gè),這里為T(mén)omcatServletWebServerFactory ServletWebServerFactory factory = getWebServerFactory(); createWebServer.tag("factory", factory.getClass().toString()); // 獲取服務(wù)器 this.webServer = factory.getWebServer(getSelfInitializer()); }
TomcatServletWebServerFactory.getWebServer
public WebServer getWebServer(ServletContextInitializer... initializers) { if (this.disableMBeanRegistry) { Registry.disableRegistry(); } Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); for (LifecycleListener listener : this.serverLifecycleListeners) { tomcat.getServer().addLifecycleListener(listener); } // 設(shè)置Connector,對(duì)應(yīng)與Tomcat Server.xml 中的<Connector></Connector> Connector connector = new Connector(this.protocol); connector.setThrowOnFailure(true); // 對(duì)應(yīng)于Server.xml 中 // <Service name="Catalina"> // <Connector port="8080" protocol="HTTP/1.1" // connectionTimeout="20000" // redirectPort="8443" relaxedQueryChars="[|]"/> // </Service> tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } // 準(zhǔn)備好Context組件 prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); }
// 創(chuàng)建Tomcat服務(wù)器 protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown()); }
至此,Tomcat配置已經(jīng)初始化完成,準(zhǔn)備啟動(dòng)。
在finishRefresh()方法中,會(huì)啟動(dòng)Tomcat
getLifecycleProcessor().onRefresh(); > DefaultLifecycleProcessor.startBeans(true); > LifecycleGroup::start > doStart(this.lifecycleBeans, member.name, this.autoStartupOnly); > bean.start(); > WebServerStartStopLifecycle.start > TomcatWebServer.start();
private void startBeans(boolean autoStartupOnly) { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new TreeMap<>(); lifecycleBeans.forEach((beanName, bean) -> { if (!autoStartupOnly || (bean instanceof SmartLifecycle smartLifecycle && smartLifecycle.isAutoStartup())) { int phase = getPhase(bean); phases.computeIfAbsent( phase, p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly) ).add(beanName, bean); } }); if (!phases.isEmpty()) { phases.values().forEach(LifecycleGroup::start); } }
public void start() { this.webServer.start(); this.running = true; this.applicationContext .publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext)); }
DispatchServlet配置
ServletContextInitializer
在prepareContext方法中,有一個(gè)方法configureContext
configureContext(context, initializersToUse);
configureContext方法,在這里面創(chuàng)建了一個(gè)TomcatStarter對(duì)象,這個(gè)類(lèi)實(shí)現(xiàn)了ServletContainerInitializer接口,所以在容器啟動(dòng)過(guò)程中會(huì)被調(diào)用。
TomcatStarter starter = new TomcatStarter(initializers); context.addServletContainerInitializer(starter, NO_CLASSES);
initializers是Spring自己定義的初始化接口ServletContextInitializer,傳入TomcatStarter之后,在onStartup方法中循環(huán)調(diào)用onStartup方法。
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { try { for (ServletContextInitializer initializer : this.initializers) { initializer.onStartup(servletContext); } } ... }
需要注意的是,這里的initializers有些傳過(guò)來(lái)的時(shí)候是一個(gè)函數(shù)式接口,在上面的factory.getWebServer(getSelfInitializer());
這里傳進(jìn)來(lái)的,就是一個(gè)函數(shù)式接口
private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() { return this::selfInitialize; }
實(shí)際調(diào)用在下面這個(gè)方法
private void selfInitialize(ServletContext servletContext) throws ServletException { prepareWebApplicationContext(servletContext); registerApplicationScope(servletContext); WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext); for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } }
這里遍歷所有的ServletContextInitializer,然后調(diào)用它的onStartup方法。
其中有一個(gè)DispatcherServletRegistrationBean,這個(gè)類(lèi)實(shí)現(xiàn)了ServletContextInitializer接口,主要是用來(lái)添加DispatchServlet。
DispatcherServletAutoConfiguration配置類(lèi)中有DispatcherServlet,DispatcherServletRegistrationBean兩個(gè)Bean。
protected static class DispatcherServletRegistrationConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties, ObjectProvider<MultipartConfigElement> multipartConfig) { // 創(chuàng)建DispatcherServletRegistrationBean,并把dispatcherServlet傳進(jìn)去 DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, webMvcProperties.getServlet().getPath()); registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup()); multipartConfig.ifAvailable(registration::setMultipartConfig); return registration; } } protected static class DispatcherServletConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public DispatcherServlet dispatcherServlet(WebMvcProperties webMvcProperties) { // 創(chuàng)建DispatcherServlet DispatcherServlet dispatcherServlet = new DispatcherServlet(); dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest()); dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest()); dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound()); dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents()); dispatcherServlet.setEnableLoggingRequestDetails(webMvcProperties.isLogRequestDetails()); return dispatcherServlet; } }
ServletContextInitializer.onStartup方法由子類(lèi)RegistrationBean實(shí)現(xiàn)
public final void onStartup(ServletContext servletContext) throws ServletException { String description = getDescription(); if (!isEnabled()) { logger.info(StringUtils.capitalize(description) + " was not registered (disabled)"); return; } // register是一個(gè)抽象方法,由子類(lèi)DynamicRegistrationBean實(shí)現(xiàn) register(description, servletContext); } protected abstract void register(String description, ServletContext servletContext);
DynamicRegistrationBean.register
protected final void register(String description, ServletContext servletContext) { // addRegistration是一個(gè)抽象方法,由子類(lèi)ServletRegistrationBean實(shí)現(xiàn) D registration = addRegistration(description, servletContext); if (registration == null) { logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)"); return; } // Servlet被添加到Context后,這里對(duì)Servlet進(jìn)行配置,如攔截路徑 configure(registration); } protected abstract D addRegistration(String description, ServletContext servletContext);
ServletRegistrationBean.addRegistration,作用類(lèi)似下面
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet>
protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); // 添加Servlet到Context中,這里的servlet就是DispatchServlet。 return servletContext.addServlet(name, this.servlet); }
ServletRegistrationBean.configure,作用類(lèi)似下面
<servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
protected void configure(ServletRegistration.Dynamic registration) { super.configure(registration); String[] urlMapping = StringUtils.toStringArray(this.urlMappings); if (urlMapping.length == 0 && this.alwaysMapUrl) { // DEFAULT_MAPPINGS默是“/” urlMapping = DEFAULT_MAPPINGS; } if (!ObjectUtils.isEmpty(urlMapping)) { // 設(shè)置mapping registration.addMapping(urlMapping); } registration.setLoadOnStartup(this.loadOnStartup); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } }
至此,DispatchServlet已配置好,后續(xù)流程和web.xml配置調(diào)用流程基本相同。
FrameworkServlet.initWebApplicationContext()
protected WebApplicationContext initWebApplicationContext() { // 此處獲取根容器,就是Spring初始化的XmlWebApplicationContext, // 在上面把它添加到了ServletContext的屬性中,標(biāo)記根容器,這里把它獲取出來(lái) // String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; // servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); // ===========上面為使用web.xml時(shí)的分析,下面為SpringBoot嵌入式Tomcat分析============ // 同樣是獲取根容器,不過(guò)一般為AnnotationConfigServletWebServerApplicationContext WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext wac = null; // 此時(shí)webApplicationContext還是null,因?yàn)镈ispatchServlet是被tomcat創(chuàng)建的,需要無(wú)參構(gòu)造器 // 構(gòu)造器中沒(méi)有設(shè)置webApplicationContext的代碼,所以此時(shí)webApplicationContext還是null // ===========上面為使用web.xml時(shí)的分析,下面為SpringBoot嵌入式Tomcat分析============ // 注意:在SpringBoot使用嵌入式Tomcat時(shí),這個(gè)webApplicationContext不為null,因?yàn)镕rameworkServlet還 // 實(shí)現(xiàn)了ApplicationContextAware接口,所以當(dāng)SpringBoot的上下文準(zhǔn)備好之后,會(huì)回調(diào)setApplicationContext方法 // 注入ApplicationContext,后面在細(xì)說(shuō) if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext cwac && !cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> set // the root application context (if any; may be null) as the parent cwac.setParent(rootContext); } configureAndRefreshWebApplicationContext(cwac); } } if (wac == null) { // No context instance was injected at construction time -> see if one // has been registered in the servlet context. If one exists, it is assumed // that the parent context (if any) has already been set and that the // user has performed any initialization such as setting the context id // 此處主要是獲取web.xml配置的WebApplicationContext // 可以通過(guò)設(shè)置參數(shù)contextAttribute來(lái)設(shè)置加載SpringMVC的ApplicationContext // 比如下面這樣。除非項(xiàng)目中有多個(gè)WebApplicationContext,需要使用其他WebApplicationContext才會(huì)用到 // 一般都是null // <context-param> // <param-name>contextAttribute</param-name> // <param-value>myWebApplicationContext</param-value> // </context-param> // ===========上面為使用web.xml時(shí)的分析,下面為SpringBoot嵌入式Tomcat分析 // 因?yàn)閣ac此時(shí)不為null,這里不會(huì)進(jìn)入 wac = findWebApplicationContext(); } if (wac == null) { // 現(xiàn)在進(jìn)入到創(chuàng)建SpringMVC的ApplicationContext流程 // 也就是加載contextConfigLocation定義的xml文件 // ===========上面為使用web.xml時(shí)的分析,下面為SpringBoot嵌入式Tomcat分析 // 因?yàn)閣ac此時(shí)不為null,這里不會(huì)進(jìn)入,所以沒(méi)有SpringMVC的容器,也就是沒(méi)有父子容器之分,SpringBoot項(xiàng)目中只有一個(gè)容器 // No context instance is defined for this servlet -> create a local one wac = createWebApplicationContext(rootContext); } if (!this.refreshEventReceived) { // Either the context is not a ConfigurableApplicationContext with refresh // support or the context injected at construction time had already been // refreshed -> trigger initial onRefresh manually here. synchronized (this.onRefreshMonitor) { // 初始化策略對(duì)象 // 比如:HandlerMapping,HandlerAdapter,ViewResolver等等 onRefresh(wac); } } if (this.publishContext) { // Publish the context as a servlet context attribute. String attrName = getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); } return wac; }
以上就是web.xml SpringBoot打包可執(zhí)行Jar運(yùn)行SpringMVC加載流程的詳細(xì)內(nèi)容,更多關(guān)于web.xml SpringBoot打包Jar的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java實(shí)現(xiàn)多級(jí)表頭和復(fù)雜表頭的導(dǎo)出功能
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)多級(jí)表頭和復(fù)雜表頭的導(dǎo)出功能的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03Java 實(shí)現(xiàn)將List平均分成若干個(gè)集合
這篇文章主要介紹了Java 實(shí)現(xiàn)將List平均分成若干個(gè)集合,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08java 交換兩個(gè)數(shù)據(jù)的方法實(shí)例詳解
這篇文章主要介紹了java 交換兩個(gè)數(shù)據(jù)的方法實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12Java Mybatis框架Dao層的實(shí)現(xiàn)與映射文件以及核心配置文件詳解分析
MyBatis 是一款優(yōu)秀的持久層框架,它支持自定義 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。MyBatis 免除了幾乎所有的 JDBC 代碼以及設(shè)置參數(shù)和獲取結(jié)果集的工作。MyBatis 可以通過(guò)簡(jiǎn)單的 XML 或注解來(lái)配置和映射原始類(lèi)型、接口和 Java POJO為數(shù)據(jù)庫(kù)中的記錄2021-10-10Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(5)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07java抓取網(wǎng)頁(yè)數(shù)據(jù)獲取網(wǎng)頁(yè)中所有的鏈接實(shí)例分享
java抓取網(wǎng)頁(yè)數(shù)據(jù)獲取網(wǎng)頁(yè)中所有的鏈接實(shí)例分享,使用方法,只要實(shí)例化HtmlParser時(shí)傳入網(wǎng)頁(yè)地址就可以了2013-12-12