Spring中事件處理的小技巧

字號:

Spring中提供一些Aware相關(guān)的接口,BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,其中最常用到的是ApplicationContextAware。實(shí)現(xiàn)ApplicationContextAware的Bean,在Bean被初始后,將會被注入 ApplicationContext的實(shí)例。ApplicationContextAware提供了publishEvent()方法,實(shí)現(xiàn)Observer(觀察者)設(shè)計(jì)模式的事件傳播機(jī),提供了針對Bean的事件傳播功能。通過Application.publishEvent方法,我們可以將事件通知系統(tǒng)內(nèi)所有的ApplicationListener。
    Spring事件處理一般過程:
    ·定義Event類,繼承org.springframework.context.ApplicationEvent.
    ·編寫發(fā)布事件類Publisher,實(shí)現(xiàn)org.springframework.context.ApplicationContextAware接口.
    ·覆蓋方法setApplicationContext(ApplicationContext applicationContext)和發(fā)布方法publish(Object obj)
    ·定義時(shí)間監(jiān)聽類EventListener,實(shí)現(xiàn)ApplicationListener接口,實(shí)現(xiàn)方法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;
    }