Spring:为什么“root”应用程序上下文和“servlet”应用程序上下文是由不同方创建的?

2024-01-19

据我了解,基于 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;
}

但为什么我们必须在不同的地方创建这两个上下文, 即 DispatcherServlet 和 ContextLoaderListener

因为这两个上下文应该是不同的,但仍然具有层次关系以便能够覆盖。通常加载的上下文使用ContextLoaderListener是属于整个应用程序的“根”上下文,而使用初始化的上下文DispatcherServlet实际上是特定于该 servlet 的。从技术上讲,您可以在一个应用程序中拥有多个 servlet,因此多个此类上下文各自特定于各自的 servlet,但具有相同的根上下文。更详细的可以看我的另一个回答here https://stackoverflow.com/questions/19619539/understanding-contexts-in-spring-mvc.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring:为什么“root”应用程序上下文和“servlet”应用程序上下文是由不同方创建的? 的相关文章

随机推荐