疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Spring中事件处理的小技巧


 

    Spring中提供一些Aware相关的接口,BeanFactoryAwareApplicationContextAwareResourceLoaderAwareServletContextAware等等,其中最常用到的是ApplicationContextAware。实现ApplicationContextAwareBean,在Bean被初始后,将会被注入ApplicationContext的实例。ApplicationContextAware提供了publishEvent()方法,实现Observer(观察者)设计模式的事件传播机,提供了针对Bean的事件传播功能。通过Application.publishEvent方法,我们可以将事件通知系统内所有的ApplicationListener

  Spring事件处理一般过程:

  ·定义Event类,继承org.springframework.context.ApplicationEvent.

  ·编写发布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口.

  ·覆盖方法setApplicationContext(ApplicationContextapplicationContext)和发布方法publish(Objectobj)

  ·定义时间监听类EventListener,实现ApplicationListener接口,实现方法onApplicationEvent(ApplicationEventevent).

  java代码

  importorg.springframework.context.ApplicationEvent;

  /**

  *定义事件信息

  *@authornew

  *

  */

  publicclassMessageEventextendsApplicationEvent{

  privateStringmessage;

  publicvoidsetMessage(Stringmessage){

  this.message=message;

  }

  publicStringgetMessage(){

  returnmessage;

  }

  publicMessageEvent(Objectsource,Stringmessage){

  super(source);

  this.message=message;

  //TODOAuto-generatedconstructorstub

  }

  privatestaticfinallongserialVersionUID=1L;

  }

  java代码

  importorg.springframework.beans.BeansException;

  importorg.springframework.context.ApplicationContext;

  importorg.springframework.context.ApplicationContextAware;

  importorg.springframework.context.support.FileSystemXmlApplicationContext;

  publicclassPublisherimplementsApplicationContextAware{

  privateApplicationContextcontext;

  @Override

  publicvoidsetApplicationContext(ApplicationContextarg0)

  throwsBeansException{

  //TODOAuto-generatedmethodstub

  this.context=arg0;

  }

  publicvoidpublish(Stringmessage){

  context.publishEvent(newMessageEvent(this,message));

  }

  publicstaticvoidmain(String[]args){

  ApplicationContextctx=newFileSystemXmlApplicationContext("src/applicationContext.xml");

  Publisherpub=(Publisher)ctx.getBean("publisher");

  pub.publish("HelloWorld!");

  pub.publish("Thequickbrownfoxjumpedoverthelazydog");

  }

  }

  java代码

  importorg.springframework.context.ApplicationEvent;

  importorg.springframework.context.ApplicationListener;

  publicclassMessageEventListenerimplementsApplicationListener{

  @Override

  publicvoidonApplicationEvent(ApplicationEventevent){

  //TODOAuto-generatedmethodstub

  if(eventinstanceofMessageEvent){

  MessageEventmsEvent=(MessageEvent)event;

  System.out.println("Received:"+msEvent.getMessage());

  }

  }

  }

  在运行期,ApplicationContext会自动在当前的所有Bean中寻找ApplicationListener接口的实现,并将其作为事件接收对象。当Application.publishEvent方法调用时,所有的ApplicationListener接口实现都会被激发,每个ApplicationListener可根据事件的类型判断是否是自己需要处理的事件,如上面的ActionListener只处理ActionEvent事件。