栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号