Spring IOC 自定义事件

在spring中我们可以自定义事件,并且可以使用ApplicationContext类型对象(就是spring容器container)来发布这个事件,事件发布之后,所有的ApplicaitonListener(监听器)实例都会被触发并调用指定方法onApplicationEvent()来处理.
例如:

自定义事件类RainEvent:

//spring容器中的自定义事件
public class RainEvent extends ApplicationEvent {
	public RainEvent(Object source) {
		super(source);
	}
}
监听器类RainListener1:

public class RainListener1 implements ApplicationListener {

	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof RainEvent) {
			System.out.println("唐僧大喊:" + event.getSource() + "赶快收衣服喽!");
		}
	}
}
监听器类RainListener2:

public class RainListener2 implements ApplicationListener {

	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof RainEvent) {
			System.out.println("我们:" + event.getSource() + "太好了不用上课了!");
		}
	}
}
上面的instanceof用法我已经在这篇: Java instanceof关键字的详解  说过,不懂得可以去看下~

配置文件event.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
	 <!-- 只需要把这俩个监听器类交给spring容器管理就可以了 -->
	<bean class="com.x.spring.test3.event.RainListener1"></bean>
	<bean class="com.x.spring.test3.event.RainListener2"></bean>
	
</beans>
测试类:

public class EventTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//自定义事件
		try {
			String path = "com/x/spring/test3/event/event.xml";
			ApplicationContext container = 
					new ClassPathXmlApplicationContext(path);
			
			/*spring容器发布事件之后,容器中的所有监听器都会调用指定方法去处理*/
			/*所以我们需要提前把监听器对象配置spring容器里面*/
			container.publishEvent(new RainEvent("下雨了"));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
运行效果:





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值