1. 程式人生 > 其它 >Spring中,觀察者模式的應用

Spring中,觀察者模式的應用

技術標籤:設計模式設計模式

它也叫,釋出訂閱模式,在Spring中應用在事件驅動和監聽器上


1. 簡介

觀察者模式,也被稱為釋出訂閱模式,觀察者關注某一物件被修改,會自動通知訂閱者,它的三大核心:觀察者被觀察的主題訂閱者

對應於Spring容器中的,觀察者是IOC容器,被訂閱的主題是事件,訂閱者是監聽器


2. 編寫監聽器

  • 實現ApplicationListener介面,必須將監聽器用@Component標註起來
@Component
public class ContextRefreshedApplicationListener implements ApplicationListener
<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("ContextRefreshedApplicationListener監聽到ContextRefreshedEvent事件!"); } }
  • 通過註解@EventListener實現
@Component
public class ContextClosedApplicationListener
{ @EventListener public void onContextClosedEvent(ContextClosedEvent event) { System.out.println("ContextClosedApplicationListener監聽到ContextClosedEvent事件!"); } }
  • 測試
public class QuickstartListenerApplication {
    
    public static void main(String[] args) throws
Exception { System.out.println("準備初始化IOC容器。。。"); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( "com.linkedbear.spring.event.a_quickstart"); System.out.println("IOC容器初始化完成。。。"); ctx.close(); System.out.println("IOC容器關閉。。。"); } }

在這裡插入圖片描述四種預設事件

  • ContextRefreshedEvent&ContextClosedEvent :IOC 容器重新整理完畢但尚未啟動,以及 IOC 容器已經關閉但尚未銷燬所有 Bean
  • ContextStartedEvent&ContextStoppedEvent