spring上下文,spring mvc上下文,以及servlet上下文的关联以及理解

来源:互联网 发布:cf抽奖辅助软件 编辑:程序博客网 时间:2024/05/21 22:31

前言

对于spring的学习来说,这三个上下文重要性不言而瑜,特别在java web的应用上,这三者的关系和运用,在这里探讨一下(水平有限,主要还理解概念上)
一、ServletContext
http://www.cnblogs.com/shiy/p/6628613.html
http://blog.csdn.net/lvzhiyuan/article/details/4664624
首先ServletContext便是servlet上下文的实例对象,我的理解是,在一个web容器中,它是一个全局的储存信息的空间,是容器级别的概念(不同于session),当web容器启动时,会为每一个WEB应用程序(webapps下的根目录就是一个应用程序)创建一块共享的存储区域。
例如http://localhost:8080/xx,所有xx/
servlet配置

    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath*:spring/*.xml</param-value>    </context-param>

ServletContext深究的话还有很多内容需要讲,这里就不深究了,附一张图来说明下:
这里写图片描述

二、spring上下文(WebApplication Context)
既然说到spring上下文,那么一定得先知道spring是如何启动的。Web程序是如何加载用使用到我们的spring。

启动顺序如
容器(tomcat)会读它的配置文件web.xml,找context-param和listener节点–>容器创建一个ServletContext(上下文),所有部分共享它–>将context-param键值对交给ServletContex,创建listener监听器.ContextLoaderListener –>启动其他
完整的代码可以简写为

<!-- 加载spring的配置文件 -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath*:spring/*.xml</param-value>    </context-param>    <!-- Creates the Spring Container shared by all Servlets and Filters -->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>

说的再通俗点就是spring帮我们完成了web的启动,如何实现的就在于
ContextLoaderListener的实现(这个可以不深究,不得不说spring的强大)
ContextLoaderListener大概帮我们做了三件事:(ServletContext已有)
1、初始化WebApplicationContext上下文环境(即IOC容器),加载context-param指定的配置文件信息到IOC容器中。WebApplicationContext在ServletContext中以键值对的形式保存
2、容器初始化web.xml中配置的servlet,为其初始化自己的上下文信息servletContext,并加载其设置的配置信息到该上下文中。将WebApplicationContext设置为它的父容器。
3、spring mvc上下文继承spring上下文(WebApplicationContext)
关系层级如下:
这里写图片描述

总结:
Servlet上下文目标对象是所有web应用,spring上下文目标对象是单个web应用(spring提供多种方式),spring mvc目标对象是单个web应用的spring mvc框架(是spring上下文的子上下文,即继承自spring上下文,所以子能够调用父的东西,反之,不可)。