基于spring的观察者模式
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                基于spring的观察者模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                簡單的說,觀察者模式,就類似于 廣播站發送廣播,和收音機的關系。多個收音機去收聽同一個廣播頻道。 在實際的業務場景中,可以是這樣的。創建訂單成功后,發布事件。然后減庫存。發送短信。調用微信。調用物流服務。等多個后續業務,都去監聽同一個事件。
定義一個事件。
package com.study.design.observer.spring;import org.springframework.context.ApplicationEvent;/*** 定義事件*/public class OrderEvent extends ApplicationEvent {public OrderEvent(Object source) {super(source);} }定義事件發布器
package com.study.design.observer.spring;import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.stereotype.Service;// 事件發布器。把事件發布到 spring容器中。 @Service public class OrderPublish implements ApplicationContextAware {private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {// 獲取spring容器,設置到私有屬性。this.applicationContext = applicationContext;}// 調用spring容器 發布事件public void publishEvent(ApplicationEvent event){applicationContext.publishEvent(event);}}?
訂單服務中,發布事件
package com.study.design.observer.spring;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;/*** 訂單操作,業務偽代碼*/ @Service public class OrderService {// 注入事件發布器 @Autowiredprivate OrderPublish orderPublish;/*** 電商 - 新訂單訂單*/public void saveOrder() {System.out.println("1、 訂單創建成功");// 創建事件 ,可以設置參數OrderEvent orderEvent = new OrderEvent(123456);// 發布事件 orderPublish.publishEvent(orderEvent);} }發短信? 監聽器 服務
package com.study.design.observer.spring;import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component;// 監聽器 ,有事件發布后,才會執行 @Component public class SmsListener implements ApplicationListener<OrderEvent> {@Overridepublic void onApplicationEvent(OrderEvent event) {// 獲取事件中的參數。System.out.println("event.getSource的值是:"+event.getSource());// 2---短信通知System.out.println("2、 調用短信發送的接口 -> 恭喜喜提羽絨被子");} }如此,就可以創建多個監聽器,進行不同的業務處理。這就是觀察者模式。
?
轉載于:https://www.cnblogs.com/itbac/p/10921041.html
總結
以上是生活随笔為你收集整理的基于spring的观察者模式的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Git的工作流程
 - 下一篇: android一体机-迅为10.1寸用于