spring学习:spring与springmvc父子容器【云图智联】

1.spring和springmvc父子容器概念介绍

在spring和springmvc进行整合的时候,一般情况下我们会使用不同的配置文件来配置spring和springmvc,因此我们的应用中会存在至少2个ApplicationContext实例,由于是在web应用中,因此最终实例化的是ApplicationContext的子接口WebApplicationContext。如下图所示:

mvc-context-hierarchy.png

上图中显示了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配置案例:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  6.     
  7.     <!—创建Root WebApplicationContext-->
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>/WEB-INF/spring/applicationContext.xml</param-value>  
  11.     </context-param>  
  12.   
  13.     <listener>  
  14.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  15.     </listener>  
  16.     
  17.     <!—创建Servlet WebApplicationContext-->
  18.     <servlet>  
  19.         <servlet-name>dispatcher</servlet-name>  
  20.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  21.         <init-param>  
  22.             <param-name>contextConfigLocation</param-name>  
  23.             <param-value>/WEB-INF/spring/spring-servlet.xml</param-value>  
  24.         </init-param>  
  25.         <load-on-startup>1</load-on-startup>  
  26.     </servlet>  
  27.     <servlet-mapping>  
  28.         <servlet-name>dispatcher</servlet-name>  
  29.         <url-pattern>/*</url-pattern>  
  30.     </servlet-mapping>  
  31.   
  32. </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 

  1. public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
  2.    //...
  3.    @Override
  4.    public void contextInitialized(ServletContextEvent event) {
  5.       initWebApplicationContext(event.getServletContext());
  6.    }
  7.    //...
  8. }

    可以看到ContextLoaderListener继承了ContextLoader类,真正的创建在操作,是在ContextLoader的initWebApplicationContext方法中完成。

org.springframework.web.context.ContextLoader#initWebApplicationContext 

  1. public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
  2.    //1、保证只能有一个ROOT WebApplicationContext
  3.    //尝试以”org.springframework.web.context.WebApplicationContext.ROOT”为key从ServletContext中查找WebApplicationContext实例
  4.    //如果已经存在,则抛出异常。
  5.    //一个典型的异常场景是在web.xml中配置了多个ContextLoaderListener,那么后初始化的ContextLoaderListener就会抛出异常
  6.    if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
  7.       throw new IllegalStateException(
  8.             "Cannot initialize context because there is already a root application context present - " +
  9.             "check whether you have multiple ContextLoader* definitions in your web.xml!");
  10.    }
  11.    
  12.    //2、打印日志,注意日志中的提示内容:"Initializing Spring root WebApplicationContext”
  13.    //这验证了我们之前的说法,ContextLoaderListener创建的是root WebApplicationContext
  14.    Log logger = LogFactory.getLog(ContextLoader.class);
  15.    servletContext.log("Initializing Spring root WebApplicationContext");
  16.    if (logger.isInfoEnabled()) {
  17.       logger.info("Root WebApplicationContext: initialization started");
  18.    }
  19.    long startTime = System.currentTimeMillis();
  20.    try {
  21.      
  22.       if (this.context == null) {
  23.          // 3 创建WebApplicationContext实现类实例。其内部首先会确定WebApplicationContext实例类型。
  24.         // 首先判断有没有<context-param>元素的<param-name>值为contextClass,如果有,则对应的<param-value>值,就是要创建的WebApplicationContext实例类型
  25.         // 如果没有指定,则默认的实现类为XmlWebApplicationContext。这是在spring-web-xxx.jar包中的ContextLoader.properties指定的
  26.         // 注意这个时候,只是创建了WebApplicationContext对象实例,还没有加载对应的spring配置文件
  27.          this.context = createWebApplicationContext(servletContext);
  28.       }
  29.       //4 XmlWebApplicationContext实现了ConfigurableWebApplicationContext接口,因此会进入if代码块
  30.       if (this.context instanceof ConfigurableWebApplicationContext) {
  31.          ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
  32.          // 4.1 由于WebApplicationContext对象实例还没有加载对应配置文件,spring上下文还没有被刷新,因此isActive返回false,进入if代码块
  33.          if (!cwac.isActive()) {
  34.             //4.2 当前ROOT WebApplicationContext的父context为null,则尝试通过loadParentContext方法获取父ApplicationContext,并设置到其中
  35.             //由于loadParentContext方法目前写死返回null,因此可以忽略4.2这个步骤。
  36.             if (cwac.getParent() == null) {
  37.                ApplicationContext parent = loadParentContext(servletContext);
  38.                cwac.setParent(parent);
  39.             }
  40.             //4.3 加载配置spring文件。根据<context-param>指定的contextConfigLocation,确定配置文件的位置。
  41.             configureAndRefreshWebApplicationContext(cwac, servletContext);
  42.          }
  43.       }
  44.       // 5、将创建的WebApplicationContext实例以”org.springframework.web.context.WebApplicationContext.ROOT”为key设置到ServletContext中
  45.       servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
  46.       ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  47.       if (ccl == ContextLoader.class.getClassLoader()) {
  48.          currentContext = this.context;
  49.       }
  50.       else if (ccl != null) {
  51.          currentContextPerThread.put(ccl, this.context);
  52.       }
  53.       if (logger.isDebugEnabled()) {
  54.          logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
  55.                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
  56.       }
  57.       if (logger.isInfoEnabled()) {
  58.          long elapsedTime = System.currentTimeMillis() - startTime;
  59.          logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
  60.       }
  61.       return this.context;
  62.    }
  63.    catch (RuntimeException ex) {
  64.       logger.error("Context initialization failed", ex);
  65.       servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
  66.       throw ex;
  67.    }
  68.    catch (Error err) {
  69.       logger.error("Context initialization failed", err);
  70.       servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
  71.       throw err;
  72.    }
  73. }

4.Servlet WebApplicationContext创建过程源码分析

DispatcherServlet负责创建Servlet WebApplicationContext,并尝试将ContextLoaderListener创建的ROOT WebApplicationContext设置为自己的parent。其类图继承关系如下所示: 

32F0091A-E822-43D9-9289-400B6744673A.png

其中HttpServletBean继承了HttpServlet,因此在应用初始化时,其init方法会被调用,如下:

org.springframework.web.servlet.HttpServletBean#init 

  1. public final void init() throws ServletException {
  2.    //...
  3.    // 这个方法在HttpServletBean中是空实现
  4.    initServletBean();
  5.    if (logger.isDebugEnabled()) {
  6.       logger.debug("Servlet '" + getServletName() + "' configured successfully");
  7.    }
  8. }

HttpServletBean的init方法中,调用了initServletBean()方法,在HttpServletBean中,这个方法是空实现。FrameworkServlet覆盖了HttpServletBean中的initServletBean方法,如下:

org.springframework.web.servlet.FrameworkServlet#initServletBean 

  1. @Override
  2. protected final void initServletBean() throws ServletException {
  3.    getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
  4.    if (this.logger.isInfoEnabled()) {
  5.       this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
  6.    }
  7.    long startTime = System.currentTimeMillis();
  8.    try {
  9.       // initWebApplicationContext方法中,创建了Servlet WebApplicationContext实例
  10.       this.webApplicationContext = initWebApplicationContext();
  11.       initFrameworkServlet();
  12.    }
  13.    catch (ServletException ex) {
  14.       this.logger.error("Context initialization failed", ex);
  15.       throw ex;
  16.    }
  17.    catch (RuntimeException ex) {
  18.       this.logger.error("Context initialization failed", ex);
  19.       throw ex;
  20.    }
  21.    if (this.logger.isInfoEnabled()) {
  22.       long elapsedTime = System.currentTimeMillis() - startTime;
  23.       this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
  24.             elapsedTime + " ms");
  25.    }
  26. }

上述代码片段中,我们可以看到通过调用FrameworkServlet的另一个方法initWebApplicationContext(),来真正创建WebApplicationContext实例,其源码如下:

org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext 

  1. protected WebApplicationContext initWebApplicationContext() {
  2.    //1 通过工具类WebApplicationContextUtils来获取Root WebApplicationContext
  3.    // 其内部以”org.springframework.web.context.WebApplicationContext.ROOT”为key从ServletContext中查找WebApplicationContext实例作为rootContext 
  4.    WebApplicationContext rootContext =
  5.          WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  6.    WebApplicationContext wac = null;
  7.    
  8.    //2、在我们的案例中是通过web.xml配置的DispatcherServlet,此时webApplicationContext为null,因此不会进入以下代码块
  9.    if (this.webApplicationContext != null) {
  10.       // A context instance was injected at construction time -> use it
  11.       wac = this.webApplicationContext;
  12.       if (wac instanceof ConfigurableWebApplicationContext) {
  13.          ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
  14.          if (!cwac.isActive()) {
  15.             // The context has not yet been refreshed -> provide services such as
  16.             // setting the parent context, setting the application context id, etc
  17.             if (cwac.getParent() == null) {
  18.                // The context instance was injected without an explicit parent -> set
  19.                // the root application context (if any; may be null) as the parent
  20.                cwac.setParent(rootContext);
  21.             }
  22.             configureAndRefreshWebApplicationContext(cwac);
  23.          }
  24.       }
  25.    }
  26.    //3 经过第二步,wac依然为null,此时尝试根据FrameServlet的contextAttribute 字段的值,从ServletContext中获取Servlet WebApplicationContext实例,在我们的案例中,contextAttribute值为空,因此这一步过后,wac依然为null
  27.    if (wac == null) {
  28.       // No context instance was injected at construction time -> see if one
  29.       // has been registered in the servlet context. If one exists, it is assumed
  30.       // that the parent context (if any) has already been set and that the
  31.       // user has performed any initialization such as setting the context id
  32.       wac = findWebApplicationContext();
  33.    }
  34.   
  35.    //4 开始真正的创建Servlet WebApplicationContext,并将rootContext设置为parent
  36.    if (wac == null) {
  37.       // No context instance is defined for this servlet -> create a local one
  38.       wac = createWebApplicationContext(rootContext);
  39.    }
  40.    if (!this.refreshEventReceived) {
  41.       // Either the context is not a ConfigurableApplicationContext with refresh
  42.       // support or the context injected at construction time had already been
  43.       // refreshed -> trigger initial onRefresh manually here.
  44.       onRefresh(wac);
  45.    }
  46.    if (this.publishContext) {
  47.       // Publish the context as a servlet context attribute.
  48.       String attrName = getServletContextAttributeName();
  49.       getServletContext().setAttribute(attrName, wac);
  50.       if (this.logger.isDebugEnabled()) {
  51.          this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
  52.                "' as ServletContext attribute with name [" + attrName + "]");
  53.       }
  54.    }
  55.    return wac;
  56. }

5.java方式配置

最后,对于Root WebApplicationContext和Servlet WebApplicationContext的创建,我们也可以通过java代码的方式进行配置。spring通过以下几个类对此提供了支持:

AbstractContextLoaderInitializer:其用于动态的往ServletContext中注册一个ContextLoaderListener,从而创建Root WebApplicationContext

AbstractDispatcherServletInitializer:其用于动态的往ServletContext中注册一个DispatcherServlet,从而创建Servlet WebApplicationContext

对应的类图继承关系如下所示: 

B8A3DA37-3375-4A3F-8311-24C9B6568521.png

AbstractAnnotationConfigDispatcherServletInitializer用于提供AbstractContextLoaderInitializer和AbstractDispatcherServletInitializer所需要的配置。

AbstractAnnotationConfigDispatcherServletInitializer中有3个抽象方法需要实现: 

  1. public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  2.     //获得创建Root WebApplicationContext所需的配置类
  3.     @Override
  4.     protected Class<?>[] getRootConfigClasses() {
  5.         return new Class<?[] { RootConfig.class };
  6.     }
  7.     //获得创建Servlet WebApplicationContext所需的配置类
  8.     @Override
  9.     protected Class<?>[] getServletConfigClasses() {
  10.         return new Class<?[] { App1Config.class };
  11.     }
  12.     //获得DispatchServlet拦截的url
  13.     @Override
  14.     protected String[] getServletMappings() {
  15.         return new String[] { "/app1/*" };
  16.     }
  17. }

免费学习视频欢迎关注云图智联:https://e.yuntuzhilian.com/ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值