2016年9月8日 星期四

[Java] Listener 簡易說明


[Java] Listener 簡易說明
相關類別
org.springframework.context.ApplicationEventPublisher
org.springframework.context.ApplicationEventPublisherAware
org.springframework.context.ApplicationEvent
org.springframework.context.ApplicationListener


Publisher(發佈者)
=> 需要有 instanse 去發佈 該 event
=> 該 類別 需實作 ApplicationEventPublisherAware
=> 該 類別 並新增一個發佈方法,發佈事件
 如:
public class EventPublisher implements ApplicationEventPublisherAware {
...
     private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    protected void publish(boolean isSuccess) {
        BaseEvent be = new BaseEvent (this, isSuccess);
        publisher.publishEvent(be);
    }


 }

Event(事件)
=> 新增一個自訂事件
BaseEvent 類別 繼承至 ApplicationEvent 為自訂事件
如:
public class BaseEvent extends ApplicationEvent {

    private static final Logger log = LoggerFactory.getLogger(BaseEvent.class);

    public BaseEvent(Object source) {
        super(source);
    }

    @Override
    public String toString() {
        return "Event: BaseEvent Occur";
    }

    public void logEvent() {
        log.info("BaseEvent is occur!");
    }

}


Listener(監聽器)
=>新增一個監聽器類別
如:
public class GlobalEventHandler implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof BaseEvent) {
            ((BaseEvent) event).logEvent();
        }
    }
}


最後 EventPublishe可在任一 method 中呼叫 當初所建立的 publish Method
監聽器即可列印出
BaseEvent is occur! 訊息




沒有留言 :

張貼留言