Spring MVC中ApplicationContext和WebApplicationContext有什么区别?

问题描述 投票:177回答:5

应用程序上下文和Web应用程序上下文之间有什么区别?

我知道WebApplicationContext用于面向Spring MVC体系结构的应用程序吗?

我想知道ApplicationContext在MVC应用程序中的用途是什么? ApplicationContext中定义了哪种bean?

spring spring-mvc applicationcontext
5个回答
219
投票

Web应用程序上下文扩展的应用程序上下文,旨在与标准javax.servlet.ServletContext配合使用,因此可以与容器进行通信。

public interface WebApplicationContext extends ApplicationContext {
    ServletContext getServletContext();
}

如果在WebApplicationContext中实例化的Bean实现了ServletContextAware接口,那么它们也将能够使用ServletContext

package org.springframework.web.context;
public interface ServletContextAware extends Aware { 
     void setServletContext(ServletContext servletContext);
}

[与ServletContext实例有很多可能的事情,例如,通过调用getResourceAsStream()方法来访问WEB-INF资源(xml配置等)。通常,在Servlet Spring应用程序的web.xml中定义的所有应用程序上下文都是Web应用程序上下文,这既适用于根Webapp上下文,也适用于Servlet的应用程序上下文。

此外,取决于Web应用程序的上下文功能,可能会使您的应用程序难以测试,并且可能需要使用MockServletContext类进行测试。

servlet与根上下文之间的差异Spring允许您构建多级应用程序上下文层次结构,因此,如果所需的bean不存在于当前应用程序上下文中,则将从父上下文中获取所需的bean。在Web应用程序中,默认情况下有两个层次结构级别,即根上下文和servlet上下文:“

这使您可以将某些服务作为整个应用程序的单例运行(Spring Security Bean和基本数据库访问服务通常位于此处),而另一项则作为相应服务中的单独服务运行,以避免Bean之间发生名称冲突。例如,一个Servlet上下文将为网页提供服务,而另一个将实现无状态Web服务。

这两个级别的分离在您使用spring servlet类时即开箱即用:要配置根应用程序上下文,应在web.xml中使用context-param标记

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
            /WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

(根应用程序上下文由在Web.xml中声明的ContextLoaderListener创建。>

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 

)和servlet

标记用于servlet应用程序上下文
<servlet>
   <servlet-name>myservlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>app-servlet.xml</param-value>
   </init-param>
</servlet>

请注意,如果省略init-param,那么在此示例中spring将使用myservlet-servlet.xml。

另请参见:Difference between applicationContext.xml and spring-servlet.xml in Spring Framework


12
投票

回到Servlet时代,web.xml只能有一个<context-param>,因此,当服务器加载应用程序时,仅创建一个上下文对象,并且该上下文中的数据在所有资源之间共享(例如:Servlet和JSP)。它与在上下文中具有数据库驱动程序名称相同,但不会更改。以类似的方式,当我们在<contex-param>中声明contextConfigLocation参数时,Spring将创建一个Application Context对象。


10
投票

接受的答案通过,但对此有官方解释:


3
投票
ApplicationContext(根应用程序上下文):每个Spring MVC Web应用程序都有一个applicationContext.xml文件,该文件配置为上下文配置的根。 Spring加载此文件并为整个应用程序创建一个applicationContext。该文件由ContextLoaderListener加载,该文件在web.xml文件中配置为上下文参数。每个Web应用程序只有一个applicationContext。

1
投票

Web应用程序上下文

© www.soinside.com 2019 - 2024. All rights reserved.