簡體   English   中英

Spring:為什么“root”應用程序上下文和“servlet”應用程序上下文是由不同的各方創建的?

[英]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創建DispatcherServletContextLoaderListener

第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的合理性。 但是為什么我們必須在不同的地方創建這兩個上下文,即DispatcherServletContextLoaderListener

如果我們想要 僅僅是准備必要的一切,為什么不直接創造兩種情況下ContextLoaderListener ,因為它可以被看作是main()整個Web應用程序的方法。 我認為這是更多的邏輯和當前的方法只會使事情復雜化。

添加1

根據@ Shailendra的回復,我畫了這個:

在此輸入圖像描述

我的理解是,Spring引入了application context概念並將它們存儲在Servlet Context Servlet Context是java servlet technolgoy引入的概念。

我猜DispatcherServlet實施應該有一個成員變量來保存keyservlet application contextservlet context 所以它可以訪問它自己的上下文。 也許關鍵是servlet名稱。

root application context應該有一個眾所周知的密鑰,以便每個人都可以訪問它。

添加2

root application context 的眾所周知的關鍵是:

(在org.springframework.web.context.WebApplicationContext

String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";

添加3

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM