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

在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>{

	@Override
	public 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>



  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值