1.SpringMvc的加載
在看文章之前,請對着代碼一起看,過程一步步流程其實很簡單,嘻嘻
在web.xml配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
解釋:配置listen的目的主要是在servlet啓動的時候,會調用監聽啓動消息,將servlet上下文初始化到WebApplictionContext容器
而該類繼承於 類ContextLoader,在初始化調用:
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
這個時候會調用 initWebApplicationContext方法,初始化默認生成XmlWebApplicationContext,一個Spring的容器,接下來看這個容器是怎麼生成,並且如何初始化容器的
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//首先校驗servlet容器是否已經初始化了spring容器
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!");
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
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) {
//如果spring容器沒有初始化,會創建一個空的容器,這裏回頭看下這裏的是如何獲取的
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);
}
//這裏設置一個容器的ID名,以及初始化Spring容器,這裏是重點
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//將spring容器的應用掛在context上下文
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.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
在上面的過程中其實已經標記處Spring容器生成時機以及初始化的時機,總的過程:
- Servlet容器啓動,觸發事件以及Listen初始化方法
- 進入initWebApplicationContext先獲取空的Spring容器對象
- Spring容器初始化
- 將已經初始化的容器對象放在Servlet的上下文,爲以後使用
接下來看下生成過程以及容器初始化
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//首先根據servlet獲取Spring容器的類,這裏會加載該類
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//利用反射調用無參構造函數,這裏需要配置web.xml文件中
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
//獲取Spring容器
protected Class<?> determineContextClass(ServletContext servletContext) {
//首先從servlet容器配置中拿類名,然後加載該類
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
//如果上下文獲取不到那麼就會從defaultStrategies中獲取,該對象讀取的是ContextLoader.properties文件,裏面內容配置的就是org.springframework.web.context.support.XmlWebApplicationContext
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
//類的加載
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
總結以上,獲取空Spring容器對象:
- 首先從Servlet容器是否配置該Spring容器的類的類名
- 如果在上下文配置那麼加載該類返回,否則
- 使用默認文件ContextLoader.properties配置的類名進行加載
- 獲取了Spring上下文類後,使用反射調用無參構造方法,生成一個空的對象
生成一個空的對象如何把我們的Spring XML文件注入進去呢?
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
//設置Spring容器的id,這裏不重要
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()));
}
}
//把servlet容器放入web Spring上下文件,這個時候其實他倆已經互相引用了
wac.setServletContext(sc);
//這個就是從容器上下文獲取Spring xml的路徑,需要在web.xml配置
//<context-param>
// <param-name>contextConfigLocation</param-name>
// <param-value>classpath:spring/context.xml</param-value>
//</context-param>
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
//將文件的路徑賦值給Spring上下文容器
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 容器的初始化,內容就設計的Spring的內容了
wac.refresh();
}
這裏初始化過程就是:
- 將Spring上下文容器以及servlet上下文容器互相引用(雖然理解這個流程是一個細節,但是功能上是很重要的)
- 從servlet容器獲取Spring的路徑,放入Spring容器中
- 調用Spring 容器的refresh方法初始化Spring
接下來看下Spring以及Servlet如何整合的,在web.xml會有以下配置
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在配置一個Servlet,在符合mapping的url請求都會走DispatchServlet,從名字可以看到他有分發的意思,先看下他繼承的接口,看下他大概起到一個什麼角色
可以看到這個這個類可以獲取Spring容器,但是更多的代碼功能是偏向於Servlet實現的,它起到了一個Servlet和Spring的一個橋樑作用 ,我們之前只使用通過繼承HttpServlet來實現我們業務功能,它的和與生命週期相關的主要是三個方法:
-
void init(ServletConfig config) throws ServletException
-
abstract void service(ServletRequest req, ServletResponse res)
-
void destroy()
涉及到Servlet生命週期的過程這裏就不詳細講解,可以參考Servlet生命週期,而從類的結構開始看,從HttpServletBean繼承了HttpServlet,重寫了 init()方法,在裏面會調用 void initServletBean()方法,而FrameworkServlet正好重寫了該方法,並且調用方法WebApplicationContext initWebApplicationContext(),重點從這裏開始:
protected WebApplicationContext initWebApplicationContext() {
//從前面可以看到我們可以從Servlet上下文拿到Spring加載的容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
//初始化的時候這個邏輯是不會走的,如果構造方法注入纔會走這個邏輯
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 //將之前創建的加載的Spring作爲當前web Spring 容器的父容器
cwac.setParent(rootContext);
}
//裏面會調用refresh方法加載Spring bean
configureAndRefreshWebApplicationContext(cwac);
}
}
}
//如果構造方法沒有注入,那麼從servlet上下文獲取
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
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.
//開始啓動加載SpringMvc的配置信息,這裏是重點
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
//將創建的Spring容器放在Servlet上下文
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;
}
以上其實做了一個事情,將創建或者獲取web的一個Spring容器,並且將之前加載的Spring容器作爲新建的容器父容器。這個地方初始化和parent的初始化區別是啥呢?對於子容器XmlWebApplicationContext重寫
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
會獲取/WEB-INF/*xml的controller的配置文件,parent加載的是
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/context.xml</param-value>
</context-param>
因爲controller依賴service層,生成controller bean是需要依賴父容器的bean注入
接下來看下onRefresh(wac)方法,可以看到我們的主角DispatchServlet主角實現了這個方法:
/**
* This implementation calls {@link #initStrategies}.
*/
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
從上面我們可以看到,通過之前創建或者獲取的Spring上下文獲取bean來初始化SpringMvc幾個組件,以上的過程可以總結爲以下幾個步奏:
- Servlet init方法初始化容器
- 獲取Servlet上下文來獲得之前已經加載的Root Spring容器
- 從Servlet上下文獲取Servlet本身獲取web Spring上下文並且設置父容器,沒有則創建一個新的
- 將新創建(獲取)的Spring容器來初始化DispatchServlet的處理組件
- 開始接受請求
子容器主要放置的是Controller層相關的bean,它可以訪問父容器的bean,但是父容器的是訪問不了子容器的內容的