`

spring中监听事件

阅读更多
  • spring里的事件为bean与bean间消息通信提供了支持,我们希望在一个bean处理完一个任务后,通知其他的bean做相应的事,此时就需要另外的Bean去监听当前bean所发生的事件
  • 定义spring的事件需做以下几件事:
  1. 自定义事件,继承ApplicationEvent
  2.  定义一个事件监听器,实现ApplicationListener
  3.  使用容器ApplicationContext来发布事件    

一.自定义事件

 

package com.zgw.event;

import org.springframework.context.ApplicationEvent;

public class EventDemo extends ApplicationEvent{

	private static final long serialVersionUID = 1L;
	private String msg;
	
	public EventDemo(Object source,String msg) {
		super(source);
		this.msg=msg;
		
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}

}

 

二.事件监听器

 

package com.zgw.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 实现ApplicationListener接口,并指定事件类型EventDemo
 * @author zan
 *
 */
@Component
public class ListenerDemo implements ApplicationListener<EventDemo> {
  
	//此方法是对消息进行处理
	public void onApplicationEvent(EventDemo event) {
		
		String msg = event.getMsg();
		
		System.out.println("我(bean-listenerDemo)接受到了bean-publisherDemo发布的消息:" + msg);

	}

}

 三.事件发布类

 

package com.zgw.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class PublisherDemo {
	//注入ApplicationContext用来发布事件
	@Autowired
	ApplicationContext applicationContext; 
	
	public void publish(String msg){
		//调用publishEvent()来发布
		applicationContext.publishEvent(new EventDemo(this, msg));
	}

}

 

     四.配置类

 

package com.zgw.event;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.zgw.event")
public class EventConfig {

}

 五.测试类

package com.zgw.event;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestEvent {

	public static void main(String[] args) {
		 AnnotationConfigApplicationContext context =
	                new AnnotationConfigApplicationContext(EventConfig.class);
		 
		 PublisherDemo publisher = context.getBean(PublisherDemo.class);
		 
		 publisher.publish("Hello application event");
		 
		 context.close();
	}
}

 运行结果如下:



 

 

 

 

 

 

 

 



 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics