1.spring和springmvc父子容器概念介紹
在spring和springmvc進行整合的時候,一般情況下我們會使用不同的配置文件來配置spring和springmvc,因此我們的應用中會存在至少2個ApplicationContext
實例,由于是在web應用中,因此最終實例化的是ApplicationContext的子接口WebApplicationContext
。如下圖所示:


上圖中顯示了2個WebApplicationContext實例,為了進行區分,分別稱之為:Servlet WebApplicationContext、Root WebApplicationContext。 其中:
Servlet WebApplicationContext:這是對J2EE三層架構中的web層進行配置,如控制器(controller)、視圖解析器(view resolvers)等相關的bean。通過spring mvc中提供的DispatchServlet
來加載配置,通常情況下,配置文件的名稱為spring-servlet.xml。
Root WebApplicationContext:這是對J2EE三層架構中的service層、dao層進行配置,如業務bean,數據源(DataSource)等。通常情況下,配置文件的名稱為applicationContext.xml。在web應用中,其一般通過ContextLoaderListener
來加載。
以下是一個web.xml配置案例:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!—創建Root WebApplicationContext-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!—創建Servlet WebApplicationContext-->
<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/spring-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>
</web-app>
在上面的配置中:
1. ContextLoaderListener會被優先初始化時,其會根據<context-param>元素中contextConfigLocation參數指定的配置文件路徑,在這里就是"/WEB-INF/spring/applicationContext.xml”,來創建WebApplicationContext實例。 并調用ServletContext的setAttribute方法,將其設置到ServletContext中,屬性的key為”org.springframework.web.context.WebApplicationContext.ROOT”,最后的”ROOT"字樣表明這是一個 Root WebApplicationContext。
2.DispatcherServlet在初始化時,會根據<init-param>元素中contextConfigLocation參數指定的配置文件路徑,即"/WEB-INF/spring/spring-servlet.xml”,來創建Servlet WebApplicationContext。同時,其會調用ServletContext的getAttribute方法來判斷是否存在Root WebApplicationContext。如果存在,則將其設置為自己的parent。這就是父子上下文(父子容器)的概念。
父子容器的作用在于,當我們嘗試從child context(即:Servlet WebApplicationContext)中獲取一個bean時,如果找不到,則會委派給parent context (即Root WebApplicationContext)來查找。
如果我們沒有通過ContextLoaderListener來創建Root WebApplicationContext,那么Servlet WebApplicationContext的parent就是null,也就是沒有parent context。
2.為什么要有父子容器
筆者理解,父子容器的作用主要是劃分框架邊界。
在J2EE三層架構中,在service層我們一般使用spring框架, 而在web層則有多種選擇,如spring mvc、struts等。因此,通常對于web層我們會使用單獨的配置文件。例如在上面的案例中,一開始我們使用spring-servlet.xml來配置web層,使用applicationContext.xml來配置service、dao層。如果現在我們想把web層從spring mvc替換成struts,那么只需要將spring-servlet.xml替換成Struts的配置文件struts.xml即可,而applicationContext.xml不需要改變。
事實上,如果你的項目確定了只使用spring和spring mvc的話,你甚至可以將service 、dao、web層的bean都放到spring-servlet.xml中進行配置,并不是一定要將service、dao層的配置單獨放到applicationContext.xml中,然后使用ContextLoaderListener來加載。在這種情況下,就沒有了Root WebApplicationContext,只有Servlet WebApplicationContext。
3.Root WebApplicationContext創建過程源碼分析
ContextLoaderListener用于創建ROOT WebApplicationContext,其實現了ServletContextListener
接口的contextInitialized和contextDestroyed方法,在web應用啟動和停止時,web容器(如tomcat)會負責回調這兩個方法。而創建Root WebApplicationContext就是在contextInitialized中完成的,相關源碼片段如下所示:
org.springframework.web.context.ContextLoaderListener
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
//...
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
//...
}
可以看到ContextLoaderListener繼承了ContextLoader
類,真正的創建在操作,是在ContextLoader的initWebApplicationContext方法中完成。
org.springframework.web.context.ContextLoader#initWebApplicationContext
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//1、保證只能有一個ROOT WebApplicationContext
//嘗試以”org.springframework.web.context.WebApplicationContext.ROOT”為key從ServletContext中查找WebApplicationContext實例
//如果已經存在,則拋出異常。
//一個典型的異常場景是在web.xml中配置了多個ContextLoaderListener,那么后初始化的ContextLoaderListener就會拋出異常
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!");
}
//2、打印日志,注意日志中的提示內容:"Initializing Spring root WebApplicationContext”
//這驗證了我們之前的說法,ContextLoaderListener創建的是root WebApplicationContext
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 {
if (this.context == null) {
// 3 創建WebApplicationContext實現類實例。其內部首先會確定WebApplicationContext實例類型。
// 首先判斷有沒有<context-param>元素的<param-name>值為contextClass,如果有,則對應的<param-value>值,就是要創建的WebApplicationContext實例類型
// 如果沒有指定,則默認的實現類為XmlWebApplicationContext。這是在spring-web-xxx.jar包中的ContextLoader.properties指定的
// 注意這個時候,只是創建了WebApplicationContext對象實例,還沒有加載對應的spring配置文件
this.context = createWebApplicationContext(servletContext);
}
//4 XmlWebApplicationContext實現了ConfigurableWebApplicationContext接口,因此會進入if代碼塊
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
// 4.1 由于WebApplicationContext對象實例還沒有加載對應配置文件,spring上下文還沒有被刷新,因此isActive返回false,進入if代碼塊
if (!cwac.isActive()) {
//4.2 當前ROOT WebApplicationContext的父context為null,則嘗試通過loadParentContext方法獲取父ApplicationContext,并設置到其中
//由于loadParentContext方法目前寫死返回null,因此可以忽略4.2這個步驟。
if (cwac.getParent() == null) {
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//4.3 加載配置spring文件。根據<context-param>指定的contextConfigLocation,確定配置文件的位置。
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 5、將創建的WebApplicationContext實例以”org.springframework.web.context.WebApplicationContext.ROOT”為key設置到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.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;
}
}
4.Servlet WebApplicationContext創建過程源碼分析
DispatcherServlet負責創建Servlet WebApplicationContext,并嘗試將ContextLoaderListener創建的ROOT WebApplicationContext設置為自己的parent。其類圖繼承關系如下所示:


其中HttpServletBean
繼承了HttpServlet
,因此在應用初始化時,其init方法會被調用,如下:
org.springframework.web.servlet.HttpServletBean#init
public final void init() throws ServletException {
//...
// 這個方法在HttpServletBean中是空實現
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
HttpServletBean的init方法中,調用了initServletBean()方法,在HttpServletBean中,這個方法是空實現。FrameworkServlet
覆蓋了HttpServletBean中的initServletBean方法,如下:
org.springframework.web.servlet.FrameworkServlet#initServletBean
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
// initWebApplicationContext方法中,創建了Servlet WebApplicationContext實例
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
上述代碼片段中,我們可以看到通過調用FrameworkServlet的另一個方法initWebApplicationContext(),來真正創建WebApplicationContext實例,其源碼如下:
org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext
protected WebApplicationContext initWebApplicationContext() {
//1 通過工具類WebApplicationContextUtils來獲取Root WebApplicationContext
// 其內部以”org.springframework.web.context.WebApplicationContext.ROOT”為key從ServletContext中查找WebApplicationContext實例作為rootContext
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
//2、在我們的案例中是通過web.xml配置的DispatcherServlet,此時webApplicationContext為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
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
//3 經過第二步,wac依然為null,此時嘗試根據FrameServlet的contextAttribute 字段的值,從ServletContext中獲取Servlet WebApplicationContext實例,在我們的案例中,contextAttribute值為空,因此這一步過后,wac依然為null
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();
}
//4 開始真正的創建Servlet WebApplicationContext,并將rootContext設置為parent
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.
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;
}
5.java方式配置
最后,對于Root WebApplicationContext和Servlet WebApplicationContext的創建,我們也可以通過java代碼的方式進行配置。spring通過以下幾個類對此提供了支持:
AbstractContextLoaderInitializer
:其用于動態的往ServletContext中注冊一個ContextLoaderListener,從而創建Root WebApplicationContext
AbstractDispatcherServletInitializer
:其用于動態的往ServletContext中注冊一個DispatcherServlet,從而創建Servlet WebApplicationContext
對應的類圖繼承關系如下所示:


AbstractAnnotationConfigDispatcherServletInitializer
用于提供AbstractContextLoaderInitializer和AbstractDispatcherServletInitializer所需要的配置。
AbstractAnnotationConfigDispatcherServletInitializer中有3個抽象方法需要實現:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//獲得創建Root WebApplicationContext所需的配置類
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?[] { RootConfig.class };
}
//獲得創建Servlet WebApplicationContext所需的配置類
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?[] { App1Config.class };
}
//獲得DispatchServlet攔截的url
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
免費學習視頻歡迎關注云圖智聯: