Spring在Web应用中的事件与使用

ApplicationContext在WEB应用中的实例化

ApplicationContext能以声明的方式创建,如使用ContextLoader。当然你也可以使用以编程的方式创建ApplicationContext实例。首先,让我们先分析ContextLoader接口及其实现。ContextLoader机制有两种方式,ContextLoaderListener 和ContextLoaderServlet,他们功能相同但是listener不能在Servlet2.3容器下使用。Servlet2.4规范中servlet context listeners需要在web应用启动并能处理初始请求时立即运行。(servlet context listener关闭的时候也是相同的)。servlet context listener是初始化Spring ApplicationContext理想的方式。
可以象下面所示例的一样使用ContextLoaderListener注册一个ApplicationContext

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- or use the ContextLoaderServlet instead of the above listener
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->


监听器首先检查contextConfigLocation参数,如果它不存在,它将使用/WEB-INF/applicationContext.xml作为默认值。如果已存在,它将使用分隔符(逗号、冒号或空格)将字符串分解成应用上下文件位置路径。可以支持ant-风格的路径模式,如/WEB-INF/*Context.xml(WEB-INF文件夹下所有以"Context.xml"结尾的文件)。或者/WEB-INF/**/*Context.xml(WEB-INF文件夹及子文件夹下的以"Context.xml"结尾的文件)。

 

ContextLoaderServlet同ContextLoaderListener一样使用'contextConfigLocation'参数。

ApplicationContext在Web应用中的获得

 

import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);

ApplicationContext事件

 

事件的处理通过ApplicationEvent类和ApplicationListener接口来提供的。如果在上下文中部署一个实现了ApplicationListener接口的bean,那么每当一个ApplicationEvent发布到ApplicationContext时,这个bean就得到通知。实质上,这是标准的Observer设计模式。

事件类型如下

使用举例:

//applicationContext.xml中部署listener bean
<bean id="workloadListener" class="WorkloadListener">
</bean>
public class WorkloadListener implements ApplicationListener{
	public void onApplicationEvent(ApplicationEvent event) {
    	if(event instanceof ContextRefreshedEvent)
    		...;
    	if(event instanceof ContextClosedEvent)
    		...;
	}
}

posted @ 2011-08-26 20:29  春文秋武  阅读(325)  评论(0编辑  收藏  举报