1、对于一个web 应用,其部署在web 容器中,web 容器提供其一个全局的上下文环境,这个上下文就是 ServletContext ,其后面的spring IoC 容器提供宿主环境

       通过这行代码就可以看出: servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

在web.xml 中会提供有 contextLoaderListener。在web 容器启动时,会触发容器初始化事件,此时 contextLoaderListener 会监听到这个事件,其 contextInitialized 方法会被调用,在这个方法中,spring 会初始化一个启动上下文,这个上下文就被称为根上下文,即 WebApplicationContext ,这是一个借口类,确切的说,其实际实现类是 XmlWebApplicaitonContext 。这个就是Spring 的Ioc 容器,其对应的Bean 定义的配置由web.xml 中的 context-param 标签指定。在这个Ioc 容器初始化完毕后,spring 以WebApplicationContext.ROOTWEBAPPLICATIONEXTATTRIBUTE 为属性key,将其存储到 servletContext 中,便于获取.

在web.xml中这个就是web容器的入口:  

 <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoaderListener继承了ContextLoader,实现了ServletContextListener接口。我们看看ContextLoader源码:

/**
* Name of servlet context parameter (i.e., {@value}) that can specify the
* config location for the root context, falling back to the implementation's
* default otherwise.
* @see org.springframework.web.context.support.XmlWebApplicationContext#DEFAULT_CONFIG_LOCATION
*/
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation"; 这个可以把响应的配置文件加载到web容器中,这个配置十分重要,可以定义

相应配置的位置。如下配置:

<!--加载spring上下文对象 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/cpic/root-context.xml</param-value>
</context-param>

/**
* Config param for the root WebApplicationContext implementation class to use: {@value}
* @see #determineContextClass(ServletContext)
* @see #createWebApplicationContext(ServletContext, ApplicationContext)
*/
public static final String CONTEXT_CLASS_PARAM = "contextClass"; //这个配置决定web容器的实现类,默认为XmlWebApplicationContext

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) ;//这个方法是重点,整个web容器的初始化,会在ContextLoaderListener中调用,分析ContextLoderListener这个类源码的时候时候回调用。

  我们来看看 ServletContextListener这个接口源码:

public interface ServletContextListener extends EventListener {
/**
** Notification that the web application initialization
** process is starting.
** All ServletContextListeners are notified of context
** initialization before any filter or servlet in the web
** application is initialized.
*/

public void contextInitialized ( ServletContextEvent sce ); //当容器的启动的时候自动加载这个方法

/**
** Notification that the servlet context is about to be shut down.
** All servlets and filters have been destroy()ed before any
** ServletContextListeners are notified of context
** destruction.
*/
public void contextDestroyed ( ServletContextEvent sce );//当容器destoryed时候调用该方法
}

我们来看看ContextLoadListener 源码:

/**
* Initialize the root web application context.

 实现了容器ServletContextListener的接口contextInitialized方法,初始化web容器
*/
@Override
public void contextInitialized(ServletContextEvent event) {  
initWebApplicationContext(event.getServletContext());
}

 

/**
* Initialize Spring's web application context for the given servlet context,
* using the application context provided at construction time, or creating a new one
* according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
* "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
* @param servletContext current servlet context
* @return the new WebApplicationContext
* @see #ContextLoader(WebApplicationContext)
* @see #CONTEXT_CLASS_PARAM
* @see #CONFIG_LOCATION_PARAM
*/
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!");
} //容器启动的时候发现已经存在web容器会出错

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) {
this.context = createWebApplicationContext(servletContext); //创建一个web容器
}
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); //在servletContext上下文中获取父容器
cwac.setParent(parent);//设置父级容器
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}

//serletContext 中设置web容器,serletContext提供了宿主环境
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;
}
}

具体web容器容器初始化过程会在springIoc 介绍

 

 

 

 

 








  

posted on 2018-03-23 15:58  蔡苗  阅读(1125)  评论(0编辑  收藏  举报