在Spring中已经定义了五个标准事件,分别介绍如下:
1)ContextRefreshedEvent:当ApplicationContext初始化或者刷新时触发该事件。
2)ContextClosedEvent:当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
3) RequestHandleEvent:在Web应用中,当一个http请求(request)结束触发该事件。
ContestStartedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
5)ContestStopedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
下面通过一个例子展示如何处理Spring内定的事件(例程3.8)。创建一个Java工程,添加Spring开发能力后,新建ioc.test包。在包中新建ApplicationEventListener类,实现ApplicationListener接口,在onApplicationEvent()方法中添加事件处理代码,如下:
在Spring配置文件中定义一个Bean,类为ApplicationEventListener,代码如下:
添加含有主方法的TesMain类,在主方法中,调用容器的相应方法,触发Spring内定事件,代码如下:
【转载地址】
http://www.blogjava.net/cmzy/archive/2008/07/25/217217.html
1)ContextRefreshedEvent:当ApplicationContext初始化或者刷新时触发该事件。
2)ContextClosedEvent:当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
3) RequestHandleEvent:在Web应用中,当一个http请求(request)结束触发该事件。
ContestStartedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
5)ContestStopedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
下面通过一个例子展示如何处理Spring内定的事件(例程3.8)。创建一个Java工程,添加Spring开发能力后,新建ioc.test包。在包中新建ApplicationEventListener类,实现ApplicationListener接口,在onApplicationEvent()方法中添加事件处理代码,如下:
package ioc.test;
2
3 //Import省略
4 public class ApplicationEventListener implements ApplicationListener {
5
6 public void onApplicationEvent(ApplicationEvent event) {
7
8 //如果是容器刷新事件
9 if(event instanceof ContextClosedEvent ){
10 System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
11 }else if(event instanceof ContextRefreshedEvent ){//如果是容器关闭事件
12 System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
13 }else if(event instanceof ContextStartedEvent ){
14 System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
15 }else if(event instanceof ContextStoppedEvent){
16 System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
17 }else{
18 System.out.println("有其它事件发生:"+event.getClass().getName());
19 }
20
21 }
22
23 }
在Spring配置文件中定义一个Bean,类为ApplicationEventListener,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans …………
<bean id="ApplicationEventListener" class="ioc.test.ApplicationEventListener" />
</beans>
添加含有主方法的TesMain类,在主方法中,调用容器的相应方法,触发Spring内定事件,代码如下:
package ioc.test;
//import省略
public class TesMain {
public static void main(String[] args) {
AbstractApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// ac.refresh();//触发ContextRefreshedEvent事件
ac.start(); //触发ContextStartedEvent事件
ac.stop(); //触发ContextStoppedEvent事件
ac.close(); //关闭容器,触发ContextClosedEvent事件
}
}
【转载地址】
http://www.blogjava.net/cmzy/archive/2008/07/25/217217.html