2

web.xml 片段:

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext-security.xml</param-value>
  </context-param>

  <!-- Processes application requests -->
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

根据这个答案

2- DispatcherServlet 上下文成为根上下文的子级。...

我的问题是了解 Spring 如何做出此决定(将 DispatcherServlet 上下文附加到根上下文)。appContext XML 文件中没有任何明确的内容来指定这一点,并且 AFAICT 没有任何内容可以在 XML 中指定来明确地建立这种关联。

当 DispatcherServlet 实例化它的 appContext 时,它如何知道调用setParent()它(SpringMVC 在没有根 appContext 的情况下工作得很好),如果已经存在多个非子 appContext,它会如何选择?

4

2 回答 2

2

DispatcherServlet 扩展了 FrameworkServlet,它具有以下代码:

    protected WebApplicationContext initWebApplicationContext() {
        WebApplicationContext rootContext =
                WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            WebApplicationContext wac = null;

which is subsequently used as:

 wac = createWebApplicationContext(rootContext);

WebApplicationContextUtils retrieve the context as:

public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
    return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}

public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
    Assert.notNull(sc, "ServletContext must not be null");
    Object attr = sc.getAttribute(attrName);
            ...
    return (WebApplicationContext) attr;
}

In a nutshell: root context stores a reference to itself in a context attribute. All FrameworkServlets will try to retrieve said context attribute and bind themselves to the retrieved root context (if defined).

于 2013-02-01T18:30:00.097 回答
1

SpringMVC ApplicationContext Hierarchy -

ApplicationContext (I)
     -ConfigurableApplicationContext (I)
     -WebApplicationContext (I)

于 2014-11-09T09:02:11.270 回答