小编典典

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

spring

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

我知道WebApplicationContext用于Spring MVC架构的应用程序吗?

我想知道ApplicationContextMVC应用程序中有什么用途?什么样的豆类被定义ApplicationContext


阅读 1331

收藏
2020-04-11

共1个答案

小编典典

Web应用程序上下文扩展了应用程序上下文,该上下文旨在与标准javax.servlet.ServletContext一起使用,因此能够与容器进行通信。

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

如果WebBean中实现ServletContextAware接口,则在WebApplicationContext中实例化的Bean也将能够使用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应用程序中,有两个层次结构级别.

这使你可以将某些服务作为整个应用程序的单例运行(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>

(根应用程序上下文由ContextLoaderListener创建,并在web.xml中声明

<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。

2020-04-11