SpringMVC ApplicationContext 层次结构

标签 spring spring-mvc hierarchy applicationcontext

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>

根据this answer :

2- The DispatcherServlet context becomes a child of the root context. ...

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

当 DispatcherServlet 实例化其 appContext 时,它如何知道对其调用 setParent() (SpringMVC 在没有根 appContext 的情况下也能正常工作),以及是否有多个非子 appContext已经存在它会如何选择?

最佳答案

DispatcherServlet 扩展了 FrameworkServlet,其代码如下:

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

随后用作:

 wac = createWebApplicationContext(rootContext);

WebApplicationContextUtils 检索上下文为:

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;
}

简而言之:根上下文在上下文属性中存储对其自身的引用。所有 FrameworkServlet 将尝试检索所述上下文属性并将自己绑定(bind)到检索到的根上下文(如果已定义)。

关于SpringMVC ApplicationContext 层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208286/

相关文章:

java - Spring @Transactional 配置 xml

java - Tomcat EOFException : Unexpected EOF read on the socket 异常

java - Reflection api - 查找子类类型

jquery - Kendo网格detailInit访问父网格

java - Spring @RequestBody json 400错误,如何更改@RequestyBody参数?

spring - 为什么从 GroovyTestCase 继承会导致 Grails 2.2 中出现 Spring 错误?

java - net.sf.ehcache.CacheException : java. io.StreamCorruptedException:无效的流 header :00000000

java - 上下文 :property-placeholder not working for multiple files

java - Spring项目无法连接数据库

javascript - 如何在 d3.js 中创建分层条形图