_010_Spring_Spring在Web应用中的使用

对于 Web 应用来说,ServletContext 对象是唯一的,一个 Web 应用,只有一个
ServletContext 对象。该对象是在 Web 应用装载时初始化的,即在 Web 应用装载时会自动执
行接口 ServletContext 的初始化方法。该初始化方法在整个应用中只会执行一次。

若将 Spring容器的创建语句放到 ServletContext 的初始化方法中执行,并将创建好的 Spring 容器作为
ServletContext 的属性放入其中。以后再需要 Spring 容器,直接读取该属性值即可。
ServletContext 对象生命周期与 Web 应用的相同。即放在其中的属性为全局属性。所以,
放入 ServletContext 中的 Spring 容器,在整个应用的生命周期中,均可被访问。这样就可以
保证 Spring 容器在 Web 应用中的唯一性了。

上述的这些工作,已经被封装在了如下的 Spring 的 Jar 包的相关 API 中:spring-web-4.2.1.RELEASE.jar

(1 )导入 Jar  包

在 Web 项 目 中 使 用 Spring , 需 要 导 入 Spring 对 Web 的 支 持 包 :
spring-web-4.2.1.RELEASE.jar。该包在 Spring 框架的解压目录下的 libs 目录中。

(2 ) 注册器 监听器 ContextLoaderListener

若 要 在 ServletContext 初 始 化 时 创 建 Spring 容 器 , 就 需 要 使 用 监 听 器 接 口
ServletContextListener 对 ServletContext 进行监听。Spring 为该监听器接口定义了一个实现类
ContextLoaderListener,专门用于在 ServletContext 初始化时创建 Spring 容器。查看源码:

 


注意,监听器是需要在 web.xml 中注册的。

(3 )指定 Spring  配置文件的位置<context-param/>
ContextLoaderListener 在对 Spring 容器进行创建时,需要加载 Spring 配置文件。其默认
的 Spring 配置文件位置与名称为:WEB-INF/applicationContext.xml。但,一般会将该配置文
件放置于项目的 classpath 下,即 src 下,所以需要在 web.xml 中对 Spring 配置文件的位置及
名称进行指定。

从监听器 ContextLoaderListener 的父类 ContextLoader 的源码中可以看到其要读取的配
置文件位置参数名称 contextConfigLocation。

(4 )修改 Spring  配置文件中映射文件路径的写法
导入的 Jar 包 spring-web 中代码要求,Spring 配置文件中映射文件的路径前必须添加
classpath:,以表示其在类路径下。

(5 )过 通过 WebApplicationContextUtils  获取 Spring  容器
工具类 WebApplicationContextUtils 有一个方法专门用于从 ServletContext 中获取 Spring
容器对象:getRequiredWebApplicationContext(ServletContext sc)
查其源码,看其调用关系,就可看到其是从 ServletContext 中读取的属性值,即 Spring
容器。

猜你喜欢

转载自blog.csdn.net/poiuyppp/article/details/81180201