SpringMVC 在WEB容器中的启动过程与web.xml配置解析

940 阅读7分钟
  1. web应用部署在web容器中,web容器(如tomcat)提供其一个全局的上下文环境,这个上下文就是 ServletContext,其为后面的spring IoC容器提供宿主环境;
  2. 在web.xml中会提供有contextLoaderListener。在web容器启动时,会触发容器初始化事件,此时contextLoaderListener会监听到这个事件,其contextInitialized方法会被调用,在这个方法中,spring会初始化一个启动上下文,这个上下文被称为根上下文,即WebApplicationContext,该接口类实际的实现类是XmlWebApplicationContext,即spring的IoC容器,其对应的Bean定义的配置由web.xml中的context-param标签指定。在此IoC容器初始化完毕后,spring以WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE为属性Key,将其存储到ServletContext中,便于获取;
//**************************************************************
//实现ServletListener接口的类初始化方法中接收到通知事件
//**************************************************************
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
protected ContextLoader createContextLoader() {
return new ContextLoader();
} 
//**************************************************************
//initWebApplicationContext(ContextLoaderListener中创建 context)
//**************************************************************

 public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
     //PS : ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebApplicationContext.class.getName() + ".ROOT" 根上下文的名称
     //PS : 默认情况下,配置文件的位置和名称是: DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml" 
     //在整个web应用中,只能有一个根上下文
     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) {
             // *****************************************************
             //在这里执行了创建WebApplicationContext的操作,后文有介绍
             //******************************************************
             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);
             }
         }
         // PS: 将根上下文放置在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;
     }
 }
 //**************************************************************
 //创建 WebApplicationContext 对象
  //**************************************************************
 protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent) {
     //根据web.xml中的配置决定使用何种WebApplicationContext。默认情况下使用XmlWebApplicationContext
     //web.xml中相关的配置context-param的名称“contextClass”
     Class<?> contextClass = determineContextClass(sc);
     if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
         throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
     }

     //实例化WebApplicationContext的实现类
     ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

     // Assign the best possible id value.
     if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
     // Servlet <= 2.4: resort to name specified in web.xml, if any.
         String servletContextName = sc.getServletContextName();
         if (servletContextName != null) {
             wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContextName);
         } else {
     wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX);
         }
     } else {
         // Servlet 2.5's getContextPath available!
         wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + sc.getContextPath());
     }

     wac.setParent(parent);

     wac.setServletContext(sc);
     //设置spring的配置文件
     wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));
     customizeContext(sc, wac);
     //spring容器初始化
     wac.refresh();
     return wac;
 }
 //***************************************************************
 //先来看一下initWebApplicationContext的实现:FrameworkServlet.java
 //***************************************************************
 protected WebApplicationContext initWebApplicationContext() {
     //先从web容器的ServletContext中查找WebApplicationContext
     WebApplicationContext wac = findWebApplicationContext();
     if (wac == null) {
         // No fixed context defined for this servlet - create a local one.
         //从ServletContext中取得根上下文
         WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
         //创建Spring MVC的上下文,并将根上下文作为起双亲上下文
         wac = createWebApplicationContext(parent);
     }

     if (!this.refreshEventReceived) {
         // Apparently not a ConfigurableApplicationContext with refresh support:
         // triggering initial onRefresh manually here.
         onRefresh(wac);
     }

     if (this.publishContext) {
         // Publish the context as a servlet context attribute.
         // 取得context在ServletContext中的名称
         String attrName = getServletContextAttributeName();
         //将Spring MVC的Context放置到ServletContext中
         getServletContext().setAttribute(attrName, wac);
         if (this.logger.isDebugEnabled()) {
             this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() + "' as ServletContext attribute with name [" + attrName + "]");
         }
     }
         return wac;
 }

DispatcherServlet上下文在初始化的时会建立自己的IoC上下文,用以持有spring mvc相关bean。利用WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE 从ServletContext 中 获取之前的根上下文(即WebApplicationContext)作为自己上下文的parent上下文。设置parent上下文之后,再初始化自己的上下文。在其initStrategies方法中可以看到,大概的工作就是初始化处理器映射、视图解析等。这个servlet自己持有的上下文默认实现类也是 xmlWebApplicationContext。初始化完毕后,spring以与servlet的名字相关属性Key,也将其存到 ServletContext 中供后续使用。这样每个servlet持有自己的上下文(即拥有自己独立的bean空间),同时,各servlet共享相同的bean,即根上下文(第2步中初始化的上下文)定义的bean。

通过initWebApplicationContext方法的调用,创建了DispatcherServlet对应的context,并将其放置到ServletContext中,这样就完成了在web容器中构建Spring IoC容器的过程

<!--/WEB-INF/web.xml 文件内容-->
<!-- Spring ApplicationContext 默认为如下地址,可以通过本参数调整 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
<!-- Spring ApplicationContext -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
<!-- spring controller Mapping -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/mvc-servlet.xml,
                classpath*:com/temp/framework/config/spring/frameworkContext.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping></span>

SpringMVC 核心Servlet结构图

servletContext

web 容器提供的全局上下文环境,为后面的 Spring IOC 提供宿主环境。

ApplicationContext

继承自BeanFactory接口,除了包含BeanFactory的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持,被推荐为Java EE应用之首选,可应用在Java APP与Java Web中。 由web.xml中提供的contextLoaderListener,在web容器启动时触发容器初始化事件,其中的 contextInitialized方法被调用时创建的根上下文(即:WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,)。采用 XmlWebApplicationContext 实现方法,作为 Spring IOC 容器,对应的 Bean 定义的配置由 web.xml 中的 context-param 标签指定。会被存储在 ServletContext 中。例如:

<!-- Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration) -->
  <!-- Configurations for the root application context (parent context) -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->
            /WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->
        </param-value>
    </context-param>

WebApplicationContext

获取根上下文(WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE ) 作为自己上下文的parent上下文,再初始化自己持有的上下文(默认实现类也是 xmlWebApplicationContext)。之后将该上下文以key-value的方式设置在 ServletContex中,以便后续使用。至此,每个 Servlet 既有自己的上下文(即独立的bean空间),又各个 Servlet 可以共享根上下文中定义的 bean。 例如:DispatcherServlet 维持自己的 ApplicationContext,默认会读取/WEB-INFO/-servlet.xml 文件,也可以在 /WEB-INF/web.xml 中的 Servlet 模块 重新配置。例如:

<!-- Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).-->
    <!-- Configurations for the DispatcherServlet application context (child context) -->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/spring/mvc/spring-mvc-servlet.xml
            </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/admin/*</url-pattern>
    </servlet-mapping>

后两种 context 的区别与关系

  1. 功能而言:ContextLoaderListener中创建ApplicationContext主要用于整个Web应用程序需要共享的一些组件,不管是使用什么表现层技术,一般如DAO层、Service层Bean、数据库的ConnectionFactory等。而由DispatcherServlet创建的ApplicationContext 只加载对Spring Web MVC有效的Bean,如Controller、HandlerMapping、HandlerAdapter等等,该初始化上下文应该只加载Web相关组件。
  2. 范围而言:在DispatcherServlet中可以引用由ContextLoaderListener所创建的ApplicationContext,而反过来不行。
  3. 实现顺序:这两个ApplicationContext都是通过ServletContext的setAttribute方法放到ServletContext中的。但是,ContextLoaderListener会先于DispatcherServlet创建ApplicationContext,DispatcherServlet在创建ApplicationContext时会先找到由ContextLoaderListener所创建的ApplicationContext,再将后者的ApplicationContext作为参数传给DispatcherServlet的ApplicationContext的setParent()方法。此后,框架又会调用ServletContext的setAttribute()方法将wac加入到ServletContext中。
  4. 查找顺序:当Spring在执行ApplicationContext的getBean时,如果在自己context中找不到对应的bean,则会在父ApplicationContext中去找。这也解释了为什么我们可以在DispatcherServlet中获取到由ContextLoaderListener对应的ApplicationContext中的bean。