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/