据我了解,基于 Spring 的 Web 应用程序初始化如下:
Step 1: Servlet container (e.g. Tomcat)
定位执行ServletContainerInitializer
,即SpringServletContainerInitializer
.
Step 2: SpringServletContainerInitializer
创造DispatcherServlet
and ContextLoaderListener
Step 3: DispatcherServlet
创造servlet application context
. And ContextLoaderListener
创造root application context
.
步骤 1 由 Servlet 3.0 规范定义。步骤2、3完全由Spring定义。
我可以看到放置的合理性web
豆子在servlet 上下文 and non-web
豆子在根上下文。但是为什么我们必须创建这两个上下文不同的地方,即DispatcherServlet
and ContextLoaderListener
?
If all我们想要的是just准备一切必要的东西,为什么不直接创建两个上下文ContextLoaderListener
因为它可以被视为main()
整个Web应用程序的方法。我认为这更符合逻辑,而目前的方法只会让事情变得更加复杂。
ADD 1
根据@Shailendra的回复,我画了这个:
我的理解是,Spring引入了application context
概念并将它们存储在Servlet Context
。 Servlet Context是java servlet技术引入的概念。
我猜是DispatcherServlet
实现应该有一个成员变量来保存key
to its servlet application context
in the servlet context
。所以它可以访问它自己的上下文。也许关键是 servlet 名称。
And the root application context
应该有一个知名密钥,以便每个人都可以访问它。
ADD 2
The 知名关键是root application context
这是:
(in org.springframework.web.context.WebApplicationContext
)
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
ADD 3
The DispatcherServlet
确实有参考它的WebApplicationContext
。它继承了以下成员FrameworkServlet
:
/** WebApplicationContext for this servlet */
private WebApplicationContext webApplicationContext;
And
public FrameworkServlet(WebApplicationContext webApplicationContext) {
this.webApplicationContext = webApplicationContext;
}