Spring 4.1.6(四)

Spring 的事件处理

ApplicationContext 管理的整个Bean 的生命周期,它在加载Bean 的过程中,会有不同类型的事件发生。

spring内置的事件描述
ContextRefreshedEvent当ApplicationContext initialized 或者 refreshed,还有就是通过ConfigurableApplicationContext 的接口调用refresh 方法触发事件
ContextStartedEvent当ConfigurableApplicationContext 的接口调用start 方法触发事件
ContextStoppedEvent当ConfigurableApplicationContext 的接口调用stop 方法触发事件
ContextClosedEvent当ConfigurableApplicationContext 的接口调用close 方法触发事件,该事件执行之后,不能够在refresh和restart,close 事件是context 生命周期的最后
RequestHandledEvent这是一个web 应用指定的事件,当发生http 请求对的时候触发

Spring 的事件处理是单线程,所以,如果事件发布,接受者没有接收到,事件流程是被阻塞的,无法继续执行。

监听context 的事件

所有的监听事件的Bean都需要实现 ApplicationListener ,同时通过泛型传入事件类型。

public class StartEventHandler implements ApplicationListener<ContextStartedEvent> {

	@Override
	public void onApplicationEvent(ContextStartedEvent event) {
		// TODO Auto-generated method stub
		System.out.println("event start");
		
	}

}

需要把监听器的Bean 配置在Xml 中:

  <bean class="test.StartEventHandler"/>

ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");//这时获取context 对象必须是ConfigurableApplicationContext  不然无法调用相应的方法去触发事件。
	    HelloWord h1 =  (HelloWord) context.getBean(HelloWord.class);
	    context.start();

其他的事件都类似,这里就不一一举例了。

自定义事件

定义事件源:

public class CustomEvent extends ApplicationEvent {

	public CustomEvent(Object source) {
		super(source);
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return "this is my custom event";
	}
    
}

事件传播:

public class CustomEventPublisher implements ApplicationEventPublisherAware {
	private ApplicationEventPublisher publisher;
	

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		// TODO Auto-generated method stub
		this.publisher = applicationEventPublisher;
		
	}
	public void publish() {
		CustomEvent ce = new CustomEvent(this);
		publisher.publishEvent(ce);//将自定义事件对象发布出去
	}

}

事件处理器:

public class CustomEventHandler implements ApplicationListener<CustomEvent> {

	@Override
	public void onApplicationEvent(CustomEvent event) {
		// TODO Auto-generated method stub
		System.out.println("start deal with my custom event");
		
	}

}
 <bean  class="test.CustomEventHandler"/>
  <bean  name="publisher" class="test.CustomEventPublisher"/>
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
		CustomEventPublisher h1 =  (CustomEventPublisher) context.getBean("publisher");
		h1.publish();//事件一旦发布,处理器捕捉到,就会进行相应处理。

版权声明:本文为venus321原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。