標籤:一個 syslog event extend 流程 class nap 監聽 conf
spring事件(application event)為Bean與Bean之間的訊息通訊添加了支援,當一個Bean處理完一個任務之後,希望另一個Bean知道並能做相應的處理,這時我們就需要另外一個Bean監聽當前Bean所發送的事件。
spring的事件需要遵循以下流程:
(1)自訂事件:繼承ApplicationEvent
(2)定義事件監聽器:實現ApplicationListener
(3)使用容器發布事件
下面是demo
事件類別
/*** * * @ClassName(類名) : DemoEvent(自訂事件) * @Description(描述) : spring的event為bean和bean之間的訊息通訊提供了支援,可以用一個bean監聽當前的bean所發送的事件 * @author(作者) :吳桂鎮 * @date (開發日期) :2017年11月22日 下午3:30:04 * */public class DemoEvent extends ApplicationEvent{ private static final long serialVersionUID = 1L; private String msg; public void sysLog() { System.out.println(msg); } public DemoEvent(Object source,String msg) { super(source); this.setMsg(msg); } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}
監聽類
/*** * * @ClassName(類名) : demoListener * @Description(描述) : 事件監聽器 * 實現ApplicationListener並制定監聽的事件類型 * @author(作者) :吳桂鎮 * @date (開發日期) :2017年11月22日 下午3:35:37 * */@Componentpublic class demoListener implements ApplicationListener<DemoEvent>{ /*** * 對訊息進行接受處理 */ @Override public void onApplicationEvent(DemoEvent event) { String msg = event.getMsg(); System.out.println("demoListener接受到了demoPublisher發布的訊息:"+msg); }}
發布類
/*** * * @ClassName(類名) : DemoPublisher * @Description(描述) : 事件發布類 * @author(作者) :吳桂鎮 * @date (開發日期) :2017年11月22日 下午3:41:13 * */@Componentpublic class DemoPublisher { @Autowired ApplicationContext context; public void published() { DemoEvent event = new DemoEvent(this, "發布成功!"); System.out.println("發部event:"+event); context.publishEvent(event); }}
測試類別
@Configuration@ComponentScan({"com.wugz.app"})public class EventConfig { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class); DemoPublisher publisher = context.getBean(DemoPublisher.class); publisher.published(); context.close(); }}
Spring 的監聽事件 ApplicationListener 和 ApplicationEvent 用法