Spring MVC 根应用上下文在Web容器中的启动及其销毁

    Ioc容器启动过程就是建立上下文的过程。Spring MVC提供了两种启动上下文的方式,一种是通过ContextLoaderListener启动的上下文,称为根上下文,每个Web应用只有一个这种上下文,是与ServletContext相伴而生的。另一个是与Web MVC相关的上下文用来保存、管理控制器DispatcherServlet需要的MVC对象,作为根上下文的子上下文,这个上下文与 DispatcherServlet启动相对应产生,因此一个Web应用可以有对个这样的上下文。这样根上下文和子上下文构成了一个层次上下文关系。

1、根应用上下文的启动
      但我们在web.xml配置了ContextLoaderListener后,如下:
 
 
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

这个 ContextLoaderListener是Spring提供,它实现了ServletContextListener接口,这个接口在Servlet API中定义,用于监听WEB应用ServletContext的启动及其销毁。

1)ContextLoaderListener类实现继承体系
 
 

    具体的启动过程是交由ContxtLoader类来完成,在ContextLoader类中,完成两个主要的任务,一个是在web容器中建立根应用上下文Ioc容器,另一个是配置并初始化这个根WebApplicationContext。

2) 根WebApplicationContext启动流程

   在web应用启动时,web容器将创建ServletContext, ServletContextListener是ServletContext的监听者,将监听相关事件。因此web应用启动,ServletContextListener将执行 contextInitialized (ServletContextEvent event)方法:
  
  
/**
 * Initialize the root web application context.
 */
@Override
public void contextInitialized(ServletContextEvent event) {
   initWebApplicationContext(event.getServletContext());
}

可以看到, contextInitialized方法中将执行委派给其基类 ContextLoader,执行 initWebApplicationContext()方法完成根上下文的创建,这个根上下文是web容器中唯一的实例,创建完成后会保存在web容器的ServletContext中,供需要时使用,索引是 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE  = WebApplicationContext. class .getName() +  ".ROOT"。
public WebApplicationContext initWebApplicationContext(ServletContext 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!");
}

   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) {
//这里创建根web上下文
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);
}
  //这里开始配置、初始化上下文
            configureAndRefreshWebApplicationContext(cwac, servletContext);
}
      }
  // 将创建的上下文放入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;
}
}

创建根web上下文如下:
  
  
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
   //这里判断确定,web上下文class,默认是org.springframework.web.context.support.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() + "]");
}
 //通过BeanUtils工具反射创建WebApplicationContext对象,并返回
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()));
}
   }

   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);
wac.refresh();
}
可以看到对上下文进行了相关配置,设置 ServletContext,设置初始化参数等,最后通过调用容器的refresh()方法启动整个容器,就像一般的IoC容器初始化过程一样。

2、根WebApplicationContext销毁流程


 在web应用销毁时,ServletContextListener将执行 contextDestroyed (ServletContextEvent event)方法:
  
  
@Override
public void contextDestroyed(ServletContextEvent event) {
   closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
该方法同样委派 其基类 ContextLoader来执行销毁操作,调用closeWebApplicationContext()方法:
  
  
public void closeWebApplicationContext(ServletContext servletContext) {
   servletContext.log("Closing Spring root WebApplicationContext");
   try {
if (this.context instanceof ConfigurableWebApplicationContext) {
  //调用容器的close()方法,关闭容器,并释放资源
         ((ConfigurableWebApplicationContext) this.context).close();
}
   }
finally {
      ClassLoader ccl = Thread.currentThread().getContextClassLoader();
      if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = null;
}
else if (ccl != null) {
currentContextPerThread.remove(ccl);
}
//移除servletContext保存的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE索引的根上下文
      servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
      if (this.parentContextRef != null) {
this.parentContextRef.release();
}
   }
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值