Spring学习笔记(六)

1、Spring事件机制:

最重要的两个东西:
1)、ApplicationEvent:容器事件
2)、ApplicationListener:监听器
3)、ApplicationContext是事件源,事件在程序中显示式触发,监听器监听到相应的事件就会做出相应的反应。

2、事件类:

package com.sxit.service;

import org.springframework.context.ApplicationEvent;

public class FishingEvent extends ApplicationEvent{

	private String address;
	private String name;
	
	public FishingEvent(Object source) {
		super(source);
	}
	
	public FishingEvent(Object source, String address, String name) {
		super(source);
		this.address = address;
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

3、监听器类:

package com.sxit.service;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class FishingListener implements ApplicationListener {

	public void onApplicationEvent(ApplicationEvent event) {
		
		if(event instanceof FishingEvent){
			FishingEvent fishEvent = (FishingEvent)event;
			System.out.println("钓鱼的事件源:"+fishEvent.getSource());
			System.out.println("钓鱼的地方是:"+fishEvent.getAddress());
			System.out.println("钓鱼的人是:"+fishEvent.getName());
		}else{
			System.out.println("容器本身的事件:"+event+";发生的时间:"+event.getTimestamp());
		}
	}
}

4、打印信息:

容器本身的事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@15eb0a9: startup date [Tue Nov 06 07:19:52 GMT 2012]; root of context hierarchy];发生的时间:1352186393023
钓鱼的事件源:事件源
钓鱼的地方是:水库
钓鱼的人是:傻逼

5、总结:

1)、配置监听器:
	<!-- 配置钓鱼监听器 实现了ApplicationListener的Bean,Spring会把它当做容器事件的监听者-->
	<bean class="com.sxit.service.FishingListener" />
2)、容器显式发布事件:
		apc.publishEvent(fishEvent);
3)、onApplicationEvent,每当容器发生任何事件,都会调用一次这个方法,项目启动创建容器的时候监听了一次,调用的是它自身事件,而显式发布钓鱼事件的时候又监听了一次,恰好此次是钓鱼事件,所以就会进入到监听器里的钓鱼逻辑中去。

    

猜你喜欢

转载自luan.iteye.com/blog/1717601
今日推荐