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

Spring事件处理一般过程:

public class MessageEvent extends ApplicationEvent {
       /**
       * 
       */
      private static final long serialVersionUID = 1L;
      private String msg;
          public MessageEvent(Object source, String msg) {
              super(source);
              this.msg = msg;
         }
         
         public String getMessage() {
             return msg;
         }
 }

 

 

 

public class Publisher implements ApplicationContextAware {
  
       private ApplicationContext ctx;
  
          public void setApplicationContext(ApplicationContext applicationContext)
                  throws BeansException {
              this.ctx = applicationContext;
  
          }
 
         public void publish(String message) {
             ctx.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");
         }
 
}

 

public class MessageEventListener implements ApplicationListener {
 
       public void onApplicationEvent(ApplicationEvent event) {
            if(event instanceof MessageEvent) {
                MessageEvent msgEvt = (MessageEvent)event;
                System.out.println("Received: " + msgEvt.getMessage());
            }
         }
 }

 

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

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

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

覆盖方法setApplicationContext(ApplicationContext applicationContext)和发布方法publish(Object obj)

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