Spring框架教程
Spring IOC控制反转
Spring AOP面向切面编程
Spring集成MyBatis
Spring事务
Spring与Web

Spring监听器的使用

举例:springweb-2 项目(在 spring-web 项目基础上修改)

对于 Web 应用来说,ServletContext 对象是唯一的,一个 Web 应用,只有一个ServletContext 对象,该对象是在 Web 应用装载时初始化的。若将 Spring 容器的创建时机,放在 ServletContext 初始化时,就可以保证 Spring 容器的创建只会执行一次,也就保证了Spring 容器在整个应用中的唯一性。

当 Spring 容器创建好后,在整个应用的生命周期过程中,Spring 容器应该是随时可以被访问的。即,Spring 容器应具有全局性。而放入 ServletContext 对象的属性,就具有应用的全局性。所以,将创建好的 Spring 容器,以属性的形式放入到 ServletContext 的空间中,就保证了 Spring 容器的全局性。

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

Step1:导入 Jar 包

在Web项目中使用Spring,需要导入Spring对Web的支持包:spring-web-RELEASE。

该包在 Spring 框架的解压目录下的 libs 目录中。

Step2:注册监听器 ContextLoaderListener

若要在ServletContext初始化时创建Spring容器,就需要使用监听器接口ServletContextListener对ServletContext进行监听。在web.xml中注册该监听器。

Spring 为该监听器接口定义了一个实现类 ContextLoaderListener,完成了两个很重要的工作:创建容器对象,并将容器对象放入到了 ServletContext 的空间中。

打开 ContextLoaderListener 的源码。看到一共四个方法,两个是构造方法,一个初始化方法,一个销毁方法。

所以,在这四个方法中较重要的方法应该就是 contextInitialized(),context 初始化方法。

跟踪 initWebApplicationContext()方法,可以看到,在其中创建了容器对象。

并且,将创建好的容器对象放入到了 ServletContext 的空间中,key 为一个常量:

WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。

Step3:指定Spring配置文件的位置

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

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

contextConfigLocation。

Step4:获取Spring容器对象

在 Servlet 中获取容器对象的常用方式有两种:

● 直接从 ServletContext 中获取

从对监听器 ContextLoaderListener 的源码分析可知,容器对象在 ServletContext 的中存放的 key 为

WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。所以,可以直接通过 ServletContext 的 getAttribute()方法,按照指定的 key 将容器对象获取到。

● 通过 WebApplicationContextUtils 获取

工具类 WebApplicationContextUtils 有一个方法专门用于从 ServletContext 中获取 Spring容器对象:

getRequiredWebApplicationContext(ServletContext sc)

查其源码,看其调用关系,就可看到其是从 ServletContext 中读取的属性值,即 Spring容器。

以上两种方式,无论使用哪种获取容器对象,刷新 success 页面后,可看到代码中使用 的 Spring 容器均为同一个对象。

全部教程