spring 容器启动和关闭执行某个动作 ApplicationContext

来源:互联网 发布:c语言编程之道 pdf 编辑:程序博客网 时间:2024/06/06 06:41
在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()方法中添加事件处理代码,如下: 

package com.tomcat360.p2p.util;import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextClosedEvent;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.context.event.ContextStartedEvent;import org.springframework.context.event.ContextStoppedEvent;public class T implements ApplicationListener<ApplicationEvent>{@Overridepublic void onApplicationEvent(ApplicationEvent event) {    if(event instanceof ContextClosedEvent ){         System.out.println(event.getClass().getSimpleName()+" 事件已发生!");            }else if(event instanceof ContextRefreshedEvent ){          System.out.println(event.getClass().getSimpleName()+" 事件已发生!");            }else if(event instanceof ContextStartedEvent ){             System.out.println(event.getClass().getSimpleName()+" 事件已发生!");        }else if(event instanceof ContextStoppedEvent){            System.out.println(event.getClass().getSimpleName()+" 事件已发生!");        }else{            System.out.println("有其它事件发生:"+event.getClass().getName());      } }}
在Spring配置文件中定义一个Bean,类为ApplicationEventListener,代码如下:

<bean id="springStartListener" class="com.tomcat360.p2p.util.T"></bean>



0 0
原创粉丝点击