当涉及到Spring MVC应用程序时,我在ApplicationContext和ServletContext之间感到困惑。我知道每个Spring Web应用程序只有一个ApplicationContext,每个Web应用程序也只有一个ServletContext。为了初始化ApplicationContext和ServletContext的值,在web.xml中,我们将在context-param标记中添加一些内容。
这一点让我很困惑。这两者之间有什么区别(我知道ApplicationContext有一些处理bean的方法)?什么时候我们会使用ApplicationContext和什么时候我们会使用ServletContext?
5条答案
按热度按时间bgibtngc1#
Servlet上下文:
它在部署Servlet应用程序时初始化,Servlet Context包含整个Servlet应用程序的所有配置(init-param、context-params等)。
应用程序上下文:
它是Spring特有的东西。它由Spring初始化。它保存了所有bean定义和bean的生命周期,这些bean都是在Spring配置文件中定义的。Servlet-Context对这些东西一无所知。
Spring中有两种类型的上下文:父上下文和子上下文。
Spring父上下文(应用上下文/根上下文)
role-purpose-of-contextloaderlistener-in-spring
Spring-ContextLoaderListener-And-DispatcherServlet-Concepts
当spring container启动时,它从配置文件中读取所有的bean定义并创建bean对象,管理bean对象的生命周期,这个配置是完全可选的。
DispatcherServlet vs ContextLoaderListener
/声明父上下文与子上下文中的spring bean
Spring子上下文(Web应用程序上下文/子上下文)
当spring web应用程序启动时,它将查找spring bean配置文件myWebApplication-servlet.xml。它将读取所有bean定义,并创建和管理bean对象的生命周期。如果父spring上下文可用,它将合并子spring上下文与父spring上下文。如果没有可用的Spring父上下文,应用程序将只有子spring上下文。
hzbexzde2#
它们是分开的东西,每个基于Servlet技术的Java web应用都有一个servlet context,不管是不是Spring应用,相比之下,ApplicationContext是Spring的东西;简单地说,它是一个存放Springbean的容器。
为了在web.xml中初始化ApplicationContext和ServletContext的值,我们将在context-param标记中添加一些内容。
如果对此引用一个示例会有所帮助,因为据我所知,context-param用于ServletContext,而不是ApplicationContext。
您可以使用
context-param
来提供根应用程序上下文配置文件的位置,如下所示。fv2wmkja3#
ApplicationContext是Spring的容器。
它用于将来自Springbean的配置连接在一起,并将它们用于应用程序。
如果要检索Springbean的信息,请使用ApplicationContext。
如果要获取/设置共享给所有Servlet的属性,请使用ServletContext。
mctunoxg4#
在Spring中,要读取特定的初始化配置文件,我们使用context-param,其预定义名称为contextConfigLocation。
但是在不包括任何框架的普通J2EE web应用程序的情况下,context-param可以从应用程序中的任何位置读取,即任何servlet、过滤器。
sanjay解释了ApplicationContext和ServletContext之间的区别
nhaq1z215#
ServletContext
与它的“封闭”ApplicationContext
不同。Java文档对ServletContext
的说明如下每个Java虚拟机的每个“web应用程序”都有一个[servlet]上下文。(“web应用程序”是安装在服务器URL名称空间(如/catalog)的特定子集下的servlet和内容的集合,可能通过.war文件安装。)
由于在同一个
AppBase
下可以有多个“web应用程序”,每个应用程序都有自己的DocBase
、WEB-INF/web.xml
等,因此肯定有一个公共的环境/上下文被所有“web应用程序”共享,这被称为ApplicationContext
.在JSF的情况下,PortletContext
是ServletContext
的相对部分,并且ApplicationContext
被称为ExternalContext
。