1 SpringMVC 配置XML的方式啟動
1.1 XML檔案配置
在servlet3.0之前我們可以通過web.xml 配置servlet和監聽器
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
1.2 啟動過程分析
Tomcat啟動會去掃描web.xml,然後會把監聽器和servlet 加入到Tomcat的ServletContext裡,首先我們看下ContextLoaderListener。ContextLoaderListener實作了Tomcat的**ServletContextListener **的接口,當Tomcat啟動時會調用
contextInitialized()
方法。
我們接下來看下ContextLoaderListener的
contextInitialized()
方法:
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
// 這裡有兩個重要方法分别為createWebApplicationContext(servletContext)
// 和configureAndRefreshWebApplicationContext(cwac, servletContext);
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
//建立WebApplicationContext對象傳回的是XmlWebApplicationContext
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!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 ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//這裡是spring容器的初始化,也是spring容器的啟動的位置
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
我們首先看下
**createWebApplicationContext**
,這裡傳回的預設是XmlWebApplicationContext。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 根據ServletContext傳回對應的 WebApplicationContext 預設為XmlWebApplicationContext
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
接下來我們看下
**configureAndRefreshWebApplicationContext**
方法:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
// 把ServletContext 放到spring容器中
wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
//這塊是不是很熟悉,spring啟動的時候就會去調refresh()方法、
//XmlWebApplicationContext繼承了AbstractApplicationContext
//是以會去調用AbstractApplicationContext的refresh()方法.
wac.refresh();
}
至此XML方式啟動就把Spring容器啟動了。這裡啟動的是spring的根容器。我們先不看DispatcherServlet 類。因為DispatcherServlet 裡也啟動一個spring web容器,它是根容器的子容器。
1.3 DispatcherServlet
DispatcherServlet 是如何起作用的呢?Tomcat啟動的時候會去加載web.xml.讀取XML的過程中就會把DispatcherServlet 添加到Tomcat容器中。是以當請求過來的時候就會調用DispatcherServlet 。再接下來其他方式啟動的時候我們會分析如何把DispatcherServlet 加入到Tomcat容器裡。
2 SpringMVC純注解模式啟動
2.1 Servlet3.0的注解開發
Servlet3.0之後我們發現就可以用純注解的模式去配置servlet。可以參考servlet3.0官方文檔:直接通過在類上注解**@WebServlet**,@WebListener,@WebFilter等注解實作Servlet 、Listener、以及Filter。
Servlet3.0還提供了新的特新,如果說 3.0 版本新增的注解支援是為了簡化 Servlet/ 過濾器 / 監聽器的聲明,進而使得 web.xml 變為可選配置, 那麼新增的可插性 (pluggability) 支援則将 Servlet 配置的靈活性提升到了新的高度。熟悉 Struts2 的開發者都知道,Struts2 通過插件的形式提供了對包括 Spring 在内的各種開發架構的支援,開發者甚至可以自己為 Struts2 開發插件,而 Servlet 的可插性支援正是基于這樣的理念而産生的。使用該特性,現在我們可以在不修改已有 Web 應用的前提下,隻需将按照一定格式打成的 JAR 包放到 WEB-INF/lib 目錄下,即可實作新功能的擴充,不需要額外的配置。
首先我們自己開發一個:
在META-INF/services目錄中的建立一個名稱為javax.servlet.ServletContainerInitializer檔案,内容是對應實作tomcat的ServletContainerInitializer類的自定義 MyServletContainerInitializer全類名
//@HandlesTypes(WebService.class) 是tomcat 的注解,會加載實作WebService類的所有子類以及抽象類
@HandlesTypes(WebService.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {
// Set<Class<?>> c 就是@HandlesTypes 加載的類
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
// 在此,使用JAX-WS 特定的代碼來初始化運作庫和設定mapping等。
ServletRegistration reg = ctx.addServlet("JAXWSServlet", "com.sun.webservice.JAXWSServlet");
//對應的攔截位址
reg.addServletMapping("/foo");
}
}
Tomcat容器啟動的時候就會調用MyServletContainerInitializer 的
** onStartup() **
方法。就會把JAXWSServlet加入到tomcat 容器中。
2.2 SpringMVC 是如何實作可插性配置的
結合Servlet3.0的新特性,我們去springweb的jar去尋找對應的javax.servlet.ServletContainerInitializer檔案。我們可以發現Spring實作的ServletContainerInitializer。
我們進去看下SpringServletContainerInitializer類:
// 會去實作查找實作WebApplicationInitializer的所有的類包括抽象類
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<>();
if (webAppInitializerClasses != null) {
for (Class<?> waiClass : webAppInitializerClasses) {
// Be defensive: Some servlet containers provide us with invalid classes,
// no matter what @HandlesTypes says...
// 判斷不是接口類或者不是抽象類然後初始化
if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)
ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
//調用子類的方法
initializer.onStartup(servletContext);
}
}
}
那我們接下來就去看下**WebApplicationInitializer **這個類,這是個接口類,是以我們要看他的實作類。
[外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-5Z1qhi1l-1612848221233)(https://tcs.teambition.net/storage/312286ff59e0a6a28ba068e261f32e20d125?Signature=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBcHBJRCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9hcHBJZCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9vcmdhbml6YXRpb25JZCI6IiIsImV4cCI6MTYxMzQ0OTEyNSwiaWF0IjoxNjEyODQ0MzI1LCJyZXNvdXJjZSI6Ii9zdG9yYWdlLzMxMjI4NmZmNTllMGE2YTI4YmEwNjhlMjYxZjMyZTIwZDEyNSJ9.aTlmx9lh0-vM6xDf2NalpUIHpgd-Xi2lBCAwxEDisoc&download=image.png “”)]
我們點選去看到他沒有實作類。那這改怎麼辦?我們參考下SpringMVC的官方文檔看下。springMVC給的文檔是讓我們實作
**WebApplicationInitializer **
開不開心?
import org.springframework.web.WebApplicationInitializer;
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
// 我們手動把DispatcherServlet加入到Tomcat容器中了。
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
或者實作**AbstractAnnotationConfigDispatcherServletInitializer **
// 掃描基于注解的類加載
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// 掃描根容器的配置類
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
// 掃描spring web 容器的 配置類
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { MyWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
這兩個配置類的作用是什麼呢? 就是 為了拆分 spring 加載類,以便于互不影響,根容器掃描getRootConfigClasses ,子容器掃描getServletConfigClasses 。spring的 dao 、service 層的加載不需要spring web容器控制。這樣如果我們把spring web MVC 直接 替換成structs 也不會影響到後端業務。我們在接下來的代碼分析中可以看到調用這兩個的地方。
再或者**AbstractDispatcherServletInitializer **
// 基于XML配置的
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
@Override
protected WebApplicationContext createServletApplicationContext() {
XmlWebApplicationContext cxt = new XmlWebApplicationContext();
cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
return cxt;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
2.3 啟動流程分析
我們分析下繼承**AbstractAnnotationConfigDispatcherServletInitializer **類的啟動流程吧。
首先看下整體UML結構圖
[外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-9RLI1SPc-1612848221237)(https://tcs.teambition.net/storage/3122d37dee3f7c58e38afffb460f00585afa?Signature=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBcHBJRCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9hcHBJZCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9vcmdhbml6YXRpb25JZCI6IiIsImV4cCI6MTYxMzQ0OTEyNSwiaWF0IjoxNjEyODQ0MzI1LCJyZXNvdXJjZSI6Ii9zdG9yYWdlLzMxMjJkMzdkZWUzZjdjNThlMzhhZmZmYjQ2MGYwMDU4NWFmYSJ9.l-Ip0L4rcTj38Wvihp9EJaXI88qMN2G_EFU838lKygM&download=image.png “”)]
1、首先tomcat啟動會去執行SpringServletContainerInitializer 調用onStartup方法。而onStartup方法裡又會去執行WebApplicationInitializer子類的onStartup方法 。子類沒有會去調用父類AbstractDispatcherServletInitializer的onStartup方法:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//調用父類的onStartup
super.onStartup(servletContext);
//注冊servlet,把DispatcherServlet添加到Tomcat中
registerDispatcherServlet(servletContext);
}
調用父類AbstractContextLoaderInitializer 的onStartup。
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerContextLoaderListener(servletContext);
}
protected void registerContextLoaderListener(ServletContext servletContext) {
// createRootApplicationContext,根容器,也就是spring容器。調用 子類的方法
WebApplicationContext rootAppContext = createRootApplicationContext();
if (rootAppContext != null) {
// 這塊ContextLoaderListener 熟悉不?和XML中配置的是一樣的,增加監聽器,servlet啟動的時候回去啟動spring容器
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
listener.setContextInitializers(getRootApplicationContextInitializers());
servletContext.addListener(listener);
}
else {
logger.debug("No ContextLoaderListener registered, as " +
"createRootApplicationContext() did not return an application context");
}
}
繼續看子類的createRootApplicationContext方法
@Override
@Nullable
protected WebApplicationContext createRootApplicationContext() {
//擷取掃描類添加到spring web容器中
Class<?>[] configClasses = getRootConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
// 初始化AnnotationConfigWebApplicationContext
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(configClasses);
return context;
}
else {
return null;
}
}
看了半天也沒看到spring調用refresh()方法。這個是什麼時候調用的呢?
看下這段代碼是不是很熟悉。
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
和XML中配置的是一樣的,增加監聽器,servlet啟動的時候會去啟動spring根容器。
接着我們走下斷點,然後我們發現其實在tomcat執行個體化servlet的時候就回去調用servlet的init方法。我們可以看到到DispatcherServlet是實作tomcat的servlet的。還發現了DispatcherServlet裡也建立了一個WebApplicationContext。這個容器是幹啥的呢?既然都已經啟動了一個spring根容器,為什麼又建立了一個容器呢?
servlet啟動時會調用servlet實作類的init方法,最終調用init方法會調用initServletBean()方法,主要看initWebApplicationContext() 方法
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
if (logger.isInfoEnabled()) {
logger.info("Initializing Servlet '" + getServletName() + "'");
}
long startTime = System.currentTimeMillis();
try {
//初始化容器
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException | RuntimeException ex) {
logger.error("Context initialization failed", ex);
throw ex;
}
if (logger.isDebugEnabled()) {
String value = this.enableLoggingRequestDetails ?
"shown which may lead to unsafe logging of potentially sensitive data" :
"masked to prevent unsafe logging of potentially sensitive data";
logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
"': request parameters and headers will be " + value);
}
if (logger.isInfoEnabled()) {
logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
}
}
protected WebApplicationContext initWebApplicationContext() {
// 擷取根容器,此時根容器已經啟動了。
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
// 判斷是否為空,此時是不為空的,添加DispatcherServlete的時候我們會分析
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!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);
}
// springweb容器的初始化
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
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
// 建立spring web的子容器
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.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
if (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
applyInitializers(wac);
wac.refresh();
}
至此springmvc純注解模式的初始化流程算是分析完畢了。
我們接下來看下DispatcherServlet 是如何添加到tomcat 的容器中的。在上邊的onStartup方法中我們看registerDispatcherServlet
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//調用父類的onStartup
super.onStartup(servletContext);
//注冊servlet,把DispatcherServlet添加到Tomcat中
registerDispatcherServlet(servletContext);
}
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return empty or null");
// 建立 spring web 子容器
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext,
"createServletApplicationContext() did not return an application " +
"context for servlet [" + servletName + "]");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
Assert.notNull(registration,
"Failed to register servlet with name '" + servletName + "'." +
"Check if there is another servlet registered under the same name.");
// 将DispatcherServlet增加到Tomcat容器中
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
//建立spring web 子容器
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
// 這就是上邊 說的掃描 spring web 子容器 需要加載類的調用我們自定義的MyWebAppInitializer 的方法。
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
rvletApplicationContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
// 這就是上邊 說的掃描 spring web 子容器 需要加載類的調用我們自定義的MyWebAppInitializer 的方法。
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
}