標籤:serial 實戰 end tms list 類型 event div 流程
Spring的事件為Bean與Bean之間的訊息通訊提供了支援,當一個Bean處理完一個任務之後,希望另外一個Bean知道並能做相應的處理,這時我們就需要讓一個Bean監聽當前Bean所發送的事件。
Spring的事件需要遵循如下流程:
- 自訂事件,整合ApplicationEvent。
- 定義事件監聽器,實現ApplicationListener。
- 使用容器發布事件。
一、自訂事件
package com.cenobitor.appevent.event;import org.springframework.context.ApplicationEvent;public class DemoEvent extends ApplicationEvent { private static final long serialVersionUID = 1L; private String msg; public DemoEvent(Object source,String msg) { super(source); this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}
二、事件監聽器
package com.cenobitor.appevent.listener;import com.cenobitor.appevent.event.DemoEvent;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;
//實現ApplicationListener介面,並指定監聽的事件類型@Componentpublic class DemoListener implements ApplicationListener<DemoEvent> { @Override
//使用onApplicationEvent方法對訊息進行接收處理 public void onApplicationEvent(DemoEvent demoEvent) { String msg = demoEvent.getMsg(); System.out.println("(bean-demoListener)接收到了bean-demoPublisher發布的訊息:"+msg); }}
三、事件發布類
package com.cenobitor.appevent.publisher;import com.cenobitor.appevent.event.DemoEvent;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;@Componentpublic class DemoPublisher { @Autowired
//注入ApplicationContext用來發布事件 ApplicationContext applicationContext; //使用ApplicationContext的publishEvent方法來發布 public void publish(String msg){ applicationContext.publishEvent(new DemoEvent(this,msg)); }}
四、運行
package com.cenobitor.appevent;import com.cenobitor.appevent.publisher.DemoPublisher;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppeventApplication.class); DemoPublisher demoPublisher = context.getBean(DemoPublisher.class); demoPublisher.publish("hello application event"); context.close(); }}
結果:(bean-demoListener)接收到了bean-demoPublisher發布的訊息:hello application event
註:摘抄自《JavaEE開發的顛覆者SpringBoot 實戰》。
SpringBoot -- 事件(Application Event)