Spring中事件处理的小本领[Java编程]
本文“Spring中事件处理的小本领[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
Spring中供应一些Aware相关的接口,BeanFactoryAware、ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,此中最常用到的是ApplicationContextAware.实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例.ApplicationContextAware供应了publishEvent()办法,实现Observer(察看者)计划情势的事件传达机,供应了针对Bean的事件传达功效.通过Application.publishEvent办法,我们可以将事件告诉系统内全部的ApplicationListener.
Spring事件处理普通历程:
·定义Event类,担当org.springframework.context.ApplicationEvent.
·编写公布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口.
·覆盖办法setApplicationContext(ApplicationContext applicationContext)和公布办法publish(Object obj)
·定义时间监听类EventListener,实现ApplicationListener接口,实现办法onApplicationEvent(ApplicationEvent event).
java 代码
import org.springframework.context.ApplicationEvent;
/**
* 定义事件信息
* @author new
*
*/
public class MessageEvent extends ApplicationEvent {
private String message;
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
public MessageEvent(Object source, String message) {
super(source);
this.message = message;
// TODO Auto-generated constructor stub
}
private static final long serialVersionUID = 1L;
}
java 代码
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Publisher implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.context = arg0;
}
public void publish(String message){
context.publishEvent(new MessageEvent(this,message));
}
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Publisher pub = (Publisher) ctx.getBean("publisher");
pub.publish("Hello World!");
pub.publish("The quick brown fox jumped over the lazy dog");
}
}
java 代码
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MessageEventListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
// TODO Auto-generated method stub
if(event instanceof MessageEvent){
MessageEvent msEvent = (MessageEvent)event;
System.out.println("Received: " + msEvent.getMessage());
}
}
}
在运行期,ApplicationContext会自动在当前的全部Bean中探求ApplicationListener接口的实现,并将其作为事件接纳对象.当Application.publishEvent办法调用时,全部的ApplicationListener接口实现城市被激起,每个ApplicationListener可按照事件的范例判断能否是自己需求处理的事件,如上面的ActionListener只处理ActionEvent事件.
以上是“Spring中事件处理的小本领[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |