[英]Spring: Why “root” application context and “servlet” application context are created by different parties?
據我所知,基於Spring的Web應用程序初始化如下:
第1步 : Servlet container (eg Tomcat)
定位ServletContainerInitializer
的實現,它是SpringServletContainerInitializer
。
第2步 : SpringServletContainerInitializer
創建DispatcherServlet
和ContextLoaderListener
第3步 : DispatcherServlet
創建servlet application context
。 ContextLoaderListener
創建root application context
。
第1步由Servlet 3.0規范定義。 第2,3步完全由Spring定義。
我可以看到將web
bean放在servlet上下文和non-web
root non-web
bean的合理性。 但是為什么我們必須在不同的地方創建這兩個上下文,即DispatcherServlet
和ContextLoaderListener
?
如果我們想要的 僅僅是准備必要的一切,為什么不直接創造兩種情況下ContextLoaderListener
,因為它可以被看作是main()
整個Web應用程序的方法。 我認為這是更多的邏輯和當前的方法只會使事情復雜化。
根據@ Shailendra的回復,我畫了這個:
我的理解是,Spring引入了application context
概念並將它們存儲在Servlet Context
。 Servlet Context是java servlet technolgoy引入的概念。
我猜DispatcherServlet
實施應該有一個成員變量來保存key
它servlet application context
在servlet context
。 所以它可以訪問它自己的上下文。 也許關鍵是servlet名稱。
root application context
應該有一個眾所周知的密鑰,以便每個人都可以訪問它。
root application context
的眾所周知的關鍵是:
(在org.springframework.web.context.WebApplicationContext
)
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
DispatcherServlet
確實引用了它的WebApplicationContext
。 它從FrameworkServlet
繼承了以下memeber:
/** WebApplicationContext for this servlet */
private WebApplicationContext webApplicationContext;
和
public FrameworkServlet(WebApplicationContext webApplicationContext) {
this.webApplicationContext = webApplicationContext;
}
但是為什么我們必須在不同的地方創建這兩個上下文,即DispatcherServlet和ContextLoaderListener
因為兩個上下文應該是不同的但是具有層次關系以便能夠覆蓋。 通常,使用ContextLoaderListener
加載的上下文是屬於整個應用程序的“root”上下文,而使用DispatcherServlet
初始化的上下文實際上是特定於該servlet的。 從技術上講,您可以在應用程序中擁有多個servlet,因此多個這樣的上下文各自特定於相應的servlet但具有相同的根上下文。 欲了解更多詳情,請參閱我的另一個答案在這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.