成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

更上層樓,基于觀察者實(shí)現(xiàn),容器事件和事件監(jiān)聽器

安全 應(yīng)用安全
在 Spring 中有一個(gè) Event 事件功能,它可以提供事件的定義、發(fā)布以及監(jiān)聽事件來完成一些自定義的動(dòng)作。

[[410041]]

本文轉(zhuǎn)載自微信公眾號(hào)「bugstack蟲洞棧」,作者小傅哥 。轉(zhuǎn)載本文請(qǐng)聯(lián)系bugstack蟲洞棧公眾號(hào)。

目錄

  • 一、前言
  • 二、目標(biāo)
  • 三、方案
  • 四、實(shí)現(xiàn)
    • 1. 工程結(jié)構(gòu)
    • 2. 定義和實(shí)現(xiàn)事件
    • 3. 事件廣播器
    • 4. 事件發(fā)布者的定義和實(shí)現(xiàn)
  • 五、測試
    • 1. 創(chuàng)建一個(gè)事件和監(jiān)聽器
    • 2. 配置文件
    • 3. 單元測試
  • 六、總結(jié)
  • 七、系列推薦

一、前言

能解耦,是多么重要的一件事情!

摔杯為號(hào)、看我眼色行事、見南面火起,這是在嘎哈么?這其實(shí)是在通過事物傳播進(jìn)行解耦引線和炸彈,僅僅是這樣的一個(gè)解耦,它放到了多少村夫莽漢,劫了法場,篡了兵權(quán)!

這樣的解耦場景在互聯(lián)網(wǎng)開發(fā)的設(shè)計(jì)中使用的也是非常頻繁,如:這里需要一個(gè)注冊(cè)完成事件推送消息、用戶下單我會(huì)發(fā)送一個(gè)MQ、收到我的支付消息就可以發(fā)貨了等等,都是依靠事件訂閱和發(fā)布以及MQ消息這樣的組件,來處理系統(tǒng)之間的調(diào)用解耦,最終通過解耦的方式來提升整體系統(tǒng)架構(gòu)的負(fù)載能力。

其實(shí)解耦思路可以理解為設(shè)計(jì)模式中觀察者模式的具體使用效果,在觀察者模式中當(dāng)對(duì)象間存在一對(duì)多關(guān)系時(shí),則使用觀察者模式,它是一種定義對(duì)象間的一種一對(duì)多的依賴關(guān)系,當(dāng)一個(gè)對(duì)象的狀態(tài)發(fā)生改變時(shí),所有依賴于它的對(duì)象都得到通知并被自動(dòng)更新。這讓我想起了我每個(gè)月的車牌搖號(hào),都會(huì)推送給我一條本月沒中簽的消息!!!

二、目標(biāo)

在 Spring 中有一個(gè) Event 事件功能,它可以提供事件的定義、發(fā)布以及監(jiān)聽事件來完成一些自定義的動(dòng)作。比如你可以定義一個(gè)新用戶注冊(cè)的事件,當(dāng)有用戶執(zhí)行注冊(cè)完成后,在事件監(jiān)聽中給用戶發(fā)送一些優(yōu)惠券和短信提醒,這樣的操作就可以把屬于基本功能的注冊(cè)和對(duì)應(yīng)的策略服務(wù)分開,降低系統(tǒng)的耦合。以后在擴(kuò)展注冊(cè)服務(wù),比如需要添加風(fēng)控策略、添加實(shí)名認(rèn)證、判斷用戶屬性等都不會(huì)影響到依賴注冊(cè)成功后執(zhí)行的動(dòng)作。

那么在本章節(jié)我們需要以觀察者模式的方式,設(shè)計(jì)和實(shí)現(xiàn) Spring Event 的容器事件和事件監(jiān)聽器功能,最終可以讓我們?cè)诂F(xiàn)有實(shí)現(xiàn)的 Spring 框架中可以定義、監(jiān)聽和發(fā)布自己的事件信息。

三、方案

其實(shí)事件的設(shè)計(jì)本身就是一種觀察者模式的實(shí)現(xiàn),它所要解決的就是一個(gè)對(duì)象狀態(tài)改變給其他對(duì)象通知的問題,而且要考慮到易用和低耦合,保證高度的協(xié)作。

在功能實(shí)現(xiàn)上我們需要定義出事件類、事件監(jiān)聽、事件發(fā)布,而這些類的功能需要結(jié)合到 Spring 的 AbstractApplicationContext#refresh(),以便于處理事件初始化和注冊(cè)事件監(jiān)聽器的操作。整體設(shè)計(jì)結(jié)構(gòu)如下圖:

  • 在整個(gè)功能實(shí)現(xiàn)過程中,仍然需要在面向用戶的應(yīng)用上下文 AbstractApplicationContext 中添加相關(guān)事件內(nèi)容,包括:初始化事件發(fā)布者、注冊(cè)事件監(jiān)聽器、發(fā)布容器刷新完成事件。
  • 使用觀察者模式定義事件類、監(jiān)聽類、發(fā)布類,同時(shí)還需要完成一個(gè)廣播器的功能,接收到事件推送時(shí)進(jìn)行分析處理符合監(jiān)聽事件接受者感興趣的事件,也就是使用 isAssignableFrom 進(jìn)行判斷。
  • isAssignableFrom 和 instanceof 相似,不過 isAssignableFrom 是用來判斷子類和父類的關(guān)系的,或者接口的實(shí)現(xiàn)類和接口的關(guān)系的,默認(rèn)所有的類的終極父類都是Object。如果A.isAssignableFrom(B)結(jié)果是true,證明B可以轉(zhuǎn)換成為A,也就是A可以由B轉(zhuǎn)換而來。

四、實(shí)現(xiàn)

1. 工程結(jié)構(gòu)

  1. small-spring-step-10 
  2. └── src 
  3.     ├── main 
  4.     │   └── java 
  5.     │       └── cn.bugstack.springframework 
  6.     │           ├── beans 
  7.     │           │   ├── factory 
  8.     │           │   │   ├── config 
  9.     │           │   │   │   ├── AutowireCapableBeanFactory.java 
  10.     │           │   │   │   ├── BeanDefinition.java 
  11.     │           │   │   │   ├── BeanFactoryPostProcessor.java 
  12.     │           │   │   │   ├── BeanPostProcessor.java 
  13.     │           │   │   │   ├── BeanReference.java 
  14.     │           │   │   │   ├── ConfigurableBeanFactory.java 
  15.     │           │   │   │   └── SingletonBeanRegistry.java 
  16.     │           │   │   ├── support 
  17.     │           │   │   │   ├── AbstractAutowireCapableBeanFactory.java 
  18.     │           │   │   │   ├── AbstractBeanDefinitionReader.java 
  19.     │           │   │   │   ├── AbstractBeanFactory.java 
  20.     │           │   │   │   ├── BeanDefinitionReader.java 
  21.     │           │   │   │   ├── BeanDefinitionRegistry.java 
  22.     │           │   │   │   ├── CglibSubclassingInstantiationStrategy.java 
  23.     │           │   │   │   ├── DefaultListableBeanFactory.java 
  24.     │           │   │   │   ├── DefaultSingletonBeanRegistry.java 
  25.     │           │   │   │   ├── DisposableBeanAdapter.java 
  26.     │           │   │   │   ├── FactoryBeanRegistrySupport.java 
  27.     │           │   │   │   ├── InstantiationStrategy.java 
  28.     │           │   │   │   └── SimpleInstantiationStrategy.java   
  29.     │           │   │   ├── support 
  30.     │           │   │   │   └── XmlBeanDefinitionReader.java 
  31.     │           │   │   ├── Aware.java 
  32.     │           │   │   ├── BeanClassLoaderAware.java 
  33.     │           │   │   ├── BeanFactory.java 
  34.     │           │   │   ├── BeanFactoryAware.java 
  35.     │           │   │   ├── BeanNameAware.java 
  36.     │           │   │   ├── ConfigurableListableBeanFactory.java 
  37.     │           │   │   ├── DisposableBean.java 
  38.     │           │   │   ├── FactoryBean.java 
  39.     │           │   │   ├── HierarchicalBeanFactory.java 
  40.     │           │   │   ├── InitializingBean.java 
  41.     │           │   │   └── ListableBeanFactory.java 
  42.     │           │   ├── BeansException.java 
  43.     │           │   ├── PropertyValue.java 
  44.     │           │   └── PropertyValues.java  
  45.     │           ├── context   
  46.     │           │   ├── event 
  47.     │           │   │   ├── AbstractApplicationEventMulticaster.java  
  48.     │           │   │   ├── ApplicationContextEvent.java  
  49.     │           │   │   ├── ApplicationEventMulticaster.java  
  50.     │           │   │   ├── ContextClosedEvent.java  
  51.     │           │   │   ├── ContextRefreshedEvent.java  
  52.     │           │   │   └── SimpleApplicationEventMulticaster.java  
  53.     │           │   ├── support 
  54.     │           │   │   ├── AbstractApplicationContext.java  
  55.     │           │   │   ├── AbstractRefreshableApplicationContext.java  
  56.     │           │   │   ├── AbstractXmlApplicationContext.java  
  57.     │           │   │   ├── ApplicationContextAwareProcessor.java  
  58.     │           │   │   └── ClassPathXmlApplicationContext.java  
  59.     │           │   ├── ApplicationContext.java  
  60.     │           │   ├── ApplicationContextAware.java  
  61.     │           │   ├── ApplicationEvent.java  
  62.     │           │   ├── ApplicationEventPublisher.java  
  63.     │           │   ├── ApplicationListener.java  
  64.     │           │   └── ConfigurableApplicationContext.java 
  65.     │           ├── core.io 
  66.     │           │   ├── ClassPathResource.java  
  67.     │           │   ├── DefaultResourceLoader.java  
  68.     │           │   ├── FileSystemResource.java  
  69.     │           │   ├── Resource.java  
  70.     │           │   ├── ResourceLoader.java  
  71.     │           │   └── UrlResource.java 
  72.     │           └── utils 
  73.     │               └── ClassUtils.java 
  74.     └── test 
  75.         └── java 
  76.             └── cn.bugstack.springframework.test 
  77.                 ├── event 
  78.                 │   ├── ContextClosedEventListener.java 
  79.                 │   ├── ContextRefreshedEventListener.java 
  80.                 │   ├── CustomEvent.java 
  81.                 │   └── CustomEventListener.java 
  82.                 └── ApiTest.java 

工程源碼:公眾號(hào)「bugstack蟲洞棧」,回復(fù):Spring 專欄,獲取完整源碼

容器事件和事件監(jiān)聽器實(shí)現(xiàn)類關(guān)系,如圖 11-2

圖 10-2

  • 以上整個(gè)類關(guān)系圖以圍繞實(shí)現(xiàn) event 事件定義、發(fā)布、監(jiān)聽功能實(shí)現(xiàn)和把事件的相關(guān)內(nèi)容使用 AbstractApplicationContext#refresh 進(jìn)行注冊(cè)和處理操作。
  • 在實(shí)現(xiàn)的過程中主要以擴(kuò)展 spring context 包為主,事件的實(shí)現(xiàn)也是在這個(gè)包下進(jìn)行擴(kuò)展的,當(dāng)然也可以看出來目前所有的實(shí)現(xiàn)內(nèi)容,仍然是以IOC為主。
  • ApplicationContext 容器繼承事件發(fā)布功能接口 ApplicationEventPublisher,并在實(shí)現(xiàn)類中提供事件監(jiān)聽功能。
  • ApplicationEventMulticaster 接口是注冊(cè)監(jiān)聽器和發(fā)布事件的廣播器,提供添加、移除和發(fā)布事件方法。
  • 最后是發(fā)布容器關(guān)閉事件,這個(gè)仍然需要擴(kuò)展到 AbstractApplicationContext#close 方法中,由注冊(cè)到虛擬機(jī)的鉤子實(shí)現(xiàn)。

2. 定義和實(shí)現(xiàn)事件

cn.bugstack.springframework.context.ApplicationEvent

  1. public abstract class ApplicationEvent extends EventObject { 
  2.  
  3.     /** 
  4.      * Constructs a prototypical Event. 
  5.      * 
  6.      * @param source The object on which the Event initially occurred. 
  7.      * @throws IllegalArgumentException if source is null
  8.      */ 
  9.     public ApplicationEvent(Object source) { 
  10.         super(source); 
  11.     } 
  12.  
  • 以繼承 java.util.EventObject 定義出具備事件功能的抽象類 ApplicationEvent,后續(xù)所有事件的類都需要繼承這個(gè)類。

cn.bugstack.springframework.context.event.ApplicationContextEvent

  1. public class ApplicationContextEvent extends ApplicationEvent { 
  2.  
  3.     /** 
  4.      * Constructs a prototypical Event. 
  5.      * 
  6.      * @param source The object on which the Event initially occurred. 
  7.      * @throws IllegalArgumentException if source is null
  8.      */ 
  9.     public ApplicationContextEvent(Object source) { 
  10.         super(source); 
  11.     } 
  12.  
  13.     /** 
  14.      * Get the <code>ApplicationContext</code> that the event was raised for
  15.      */ 
  16.     public final ApplicationContext getApplicationContext() { 
  17.         return (ApplicationContext) getSource(); 
  18.     } 
  19.  

cn.bugstack.springframework.context.event.ContextClosedEvent

  1. public class ContextClosedEvent extends ApplicationContextEvent{ 
  2.  
  3.     /** 
  4.      * Constructs a prototypical Event. 
  5.      * 
  6.      * @param source The object on which the Event initially occurred. 
  7.      * @throws IllegalArgumentException if source is null
  8.      */ 
  9.     public ContextClosedEvent(Object source) { 
  10.         super(source); 
  11.     } 
  12.  

cn.bugstack.springframework.context.event.ContextRefreshedEvent

  1. public class ContextRefreshedEvent extends ApplicationContextEvent{ 
  2.     /** 
  3.      * Constructs a prototypical Event. 
  4.      * 
  5.      * @param source The object on which the Event initially occurred. 
  6.      * @throws IllegalArgumentException if source is null
  7.      */ 
  8.     public ContextRefreshedEvent(Object source) { 
  9.         super(source); 
  10.     } 
  11.  
  • ApplicationContextEvent 是定義事件的抽象類,所有的事件包括關(guān)閉、刷新,以及用戶自己實(shí)現(xiàn)的事件,都需要繼承這個(gè)類。
  • ContextClosedEvent、ContextRefreshedEvent,分別是 Spring 框架自己實(shí)現(xiàn)的兩個(gè)事件類,可以用于監(jiān)聽刷新和關(guān)閉動(dòng)作。

3. 事件廣播器

cn.bugstack.springframework.context.event.ApplicationEventMulticaster

  1. public interface ApplicationEventMulticaster { 
  2.  
  3.     /** 
  4.      * Add a listener to be notified of all events. 
  5.      * @param listener the listener to add 
  6.      */ 
  7.     void addApplicationListener(ApplicationListener<?> listener); 
  8.  
  9.     /** 
  10.      * Remove a listener from the notification list. 
  11.      * @param listener the listener to remove 
  12.      */ 
  13.     void removeApplicationListener(ApplicationListener<?> listener); 
  14.  
  15.     /** 
  16.      * Multicast the given application event to appropriate listeners. 
  17.      * @param event the event to multicast 
  18.      */ 
  19.     void multicastEvent(ApplicationEvent event); 
  20.  
  • 在事件廣播器中定義了添加監(jiān)聽和刪除監(jiān)聽的方法以及一個(gè)廣播事件的方法 multicastEvent 最終推送時(shí)間消息也會(huì)經(jīng)過這個(gè)接口方法來處理誰該接收事件。

cn.bugstack.springframework.context.event.AbstractApplicationEventMulticaster

  1. public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanFactoryAware { 
  2.  
  3.     public final Set<ApplicationListener<ApplicationEvent>> applicationListeners = new LinkedHashSet<>(); 
  4.  
  5.     private BeanFactory beanFactory; 
  6.  
  7.     @Override 
  8.     public void addApplicationListener(ApplicationListener<?> listener) { 
  9.         applicationListeners.add((ApplicationListener<ApplicationEvent>) listener); 
  10.     } 
  11.  
  12.     @Override 
  13.     public void removeApplicationListener(ApplicationListener<?> listener) { 
  14.         applicationListeners.remove(listener); 
  15.     } 
  16.  
  17.     @Override 
  18.     public final void setBeanFactory(BeanFactory beanFactory) { 
  19.         this.beanFactory = beanFactory; 
  20.     } 
  21.  
  22.     protected Collection<ApplicationListener> getApplicationListeners(ApplicationEvent event) { 
  23.         LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>(); 
  24.         for (ApplicationListener<ApplicationEvent> listener : applicationListeners) { 
  25.             if (supportsEvent(listener, event)) allListeners.add(listener); 
  26.         } 
  27.         return allListeners; 
  28.     } 
  29.  
  30.     /** 
  31.      * 監(jiān)聽器是否對(duì)該事件感興趣 
  32.      */ 
  33.     protected boolean supportsEvent(ApplicationListener<ApplicationEvent> applicationListener, ApplicationEvent event) { 
  34.         Class<? extends ApplicationListener> listenerClass = applicationListener.getClass(); 
  35.  
  36.         // 按照 CglibSubclassingInstantiationStrategy、SimpleInstantiationStrategy 不同的實(shí)例化類型,需要判斷后獲取目標(biāo) class 
  37.         Class<?> targetClass = ClassUtils.isCglibProxyClass(listenerClass) ? listenerClass.getSuperclass() : listenerClass; 
  38.         Type genericInterface = targetClass.getGenericInterfaces()[0]; 
  39.  
  40.         Type actualTypeArgument = ((ParameterizedType) genericInterface).getActualTypeArguments()[0]; 
  41.         String className = actualTypeArgument.getTypeName(); 
  42.         Class<?> eventClassName; 
  43.         try { 
  44.             eventClassName = Class.forName(className); 
  45.         } catch (ClassNotFoundException e) { 
  46.             throw new BeansException("wrong event class name: " + className); 
  47.         } 
  48.         // 判定此 eventClassName 對(duì)象所表示的類或接口與指定的 event.getClass() 參數(shù)所表示的類或接口是否相同,或是否是其超類或超接口。 
  49.         // isAssignableFrom是用來判斷子類和父類的關(guān)系的,或者接口的實(shí)現(xiàn)類和接口的關(guān)系的,默認(rèn)所有的類的終極父類都是Object。如果A.isAssignableFrom(B)結(jié)果是true,證明B可以轉(zhuǎn)換成為A,也就是A可以由B轉(zhuǎn)換而來。 
  50.         return eventClassName.isAssignableFrom(event.getClass()); 
  51.     } 
  52.  
  • AbstractApplicationEventMulticaster 是對(duì)事件廣播器的公用方法提取,在這個(gè)類中可以實(shí)現(xiàn)一些基本功能,避免所有直接實(shí)現(xiàn)接口放還需要處理細(xì)節(jié)。
  • 除了像 addApplicationListener、removeApplicationListener,這樣的通用方法,這里這個(gè)類中主要是對(duì) getApplicationListeners 和 supportsEvent 的處理。
  • getApplicationListeners 方法主要是摘取符合廣播事件中的監(jiān)聽處理器,具體過濾動(dòng)作在 supportsEvent 方法中。
  • 在 supportsEvent 方法中,主要包括對(duì)Cglib、Simple不同實(shí)例化需要獲取目標(biāo)Class,Cglib代理類需要獲取父類的Class,普通實(shí)例化的不需要。接下來就是通過提取接口和對(duì)應(yīng)的 ParameterizedType 和 eventClassName,方便最后確認(rèn)是否為子類和父類的關(guān)系,以此證明此事件歸這個(gè)符合的類處理。可以參考代碼中的注釋

supportsEvent 方法運(yùn)行截圖

  • 在代碼調(diào)試中可以看到,最終 eventClassName 和 event.getClass() 在 isAssignableFrom 判斷下為 true
  • 關(guān)于 CglibSubclassingInstantiationStrategy、SimpleInstantiationStrategy 可以嘗試在 AbstractApplicationContext 類中更換驗(yàn)證。

4. 事件發(fā)布者的定義和實(shí)現(xiàn)

cn.bugstack.springframework.context.ApplicationEventPublisher

  1. public interface ApplicationEventPublisher { 
  2.  
  3.     /** 
  4.      * Notify all listeners registered with this application of an application 
  5.      * event. Events may be framework events (such as RequestHandledEvent) 
  6.      * or application-specific events. 
  7.      * @param event the event to publish 
  8.      */ 
  9.     void publishEvent(ApplicationEvent event); 
  10.  
  • ApplicationEventPublisher 是整個(gè)一個(gè)事件的發(fā)布接口,所有的事件都需要從這個(gè)接口發(fā)布出去。
  1. public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext { 
  2.  
  3.     public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster"
  4.  
  5.     private ApplicationEventMulticaster applicationEventMulticaster; 
  6.  
  7.     @Override 
  8.     public void refresh() throws BeansException { 
  9.  
  10.         // 6. 初始化事件發(fā)布者 
  11.         initApplicationEventMulticaster(); 
  12.  
  13.         // 7. 注冊(cè)事件監(jiān)聽器 
  14.         registerListeners(); 
  15.  
  16.         // 9. 發(fā)布容器刷新完成事件 
  17.         finishRefresh(); 
  18.     } 
  19.  
  20.     private void initApplicationEventMulticaster() { 
  21.         ConfigurableListableBeanFactory beanFactory = getBeanFactory(); 
  22.         applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); 
  23.         beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, applicationEventMulticaster); 
  24.     } 
  25.  
  26.     private void registerListeners() { 
  27.         Collection<ApplicationListener> applicationListeners = getBeansOfType(ApplicationListener.class).values(); 
  28.         for (ApplicationListener listener : applicationListeners) { 
  29.             applicationEventMulticaster.addApplicationListener(listener); 
  30.         } 
  31.     } 
  32.  
  33.     private void finishRefresh() { 
  34.         publishEvent(new ContextRefreshedEvent(this)); 
  35.     } 
  36.  
  37.     @Override 
  38.     public void publishEvent(ApplicationEvent event) { 
  39.         applicationEventMulticaster.multicastEvent(event); 
  40.     } 
  41.  
  42.     @Override 
  43.     public void close() { 
  44.         // 發(fā)布容器關(guān)閉事件 
  45.         publishEvent(new ContextClosedEvent(this)); 
  46.  
  47.         // 執(zhí)行銷毀單例bean的銷毀方法 
  48.         getBeanFactory().destroySingletons(); 
  49.     } 
  50.  
  • 在抽象應(yīng)用上下文 AbstractApplicationContext#refresh 中,主要新增了 初始化事件發(fā)布者、注冊(cè)事件監(jiān)聽器、發(fā)布容器刷新完成事件,三個(gè)方法用于處理事件操作。
  • 初始化事件發(fā)布者(initApplicationEventMulticaster),主要用于實(shí)例化一個(gè) SimpleApplicationEventMulticaster,這是一個(gè)事件廣播器。
  • 注冊(cè)事件監(jiān)聽器(registerListeners),通過 getBeansOfType 方法獲取到所有從 spring.xml 中加載到的事件配置 Bean 對(duì)象。
  • 發(fā)布容器刷新完成事件(finishRefresh),發(fā)布了第一個(gè)服務(wù)器啟動(dòng)完成后的事件,這個(gè)事件通過 publishEvent 發(fā)布出去,其實(shí)也就是調(diào)用了 applicationEventMulticaster.multicastEvent(event); 方法。
  • 最后是一個(gè) close 方法中,新增加了發(fā)布一個(gè)容器關(guān)閉事件。publishEvent(new ContextClosedEvent(this));

五、測試

1. 創(chuàng)建一個(gè)事件和監(jiān)聽器

cn.bugstack.springframework.test.event.CustomEvent

  1. public class CustomEvent extends ApplicationContextEvent { 
  2.  
  3.     private Long id; 
  4.     private String message; 
  5.  
  6.     /** 
  7.      * Constructs a prototypical Event. 
  8.      * 
  9.      * @param source The object on which the Event initially occurred. 
  10.      * @throws IllegalArgumentException if source is null
  11.      */ 
  12.     public CustomEvent(Object source, Long id, String message) { 
  13.         super(source); 
  14.         this.id = id; 
  15.         this.message = message; 
  16.     } 
  17.  
  18.     // ...get/set 
  • 創(chuàng)建一個(gè)自定義事件,在事件類的構(gòu)造函數(shù)中可以添加自己的想要的入?yún)⑿畔ⅰ_@個(gè)事件類最終會(huì)被完成的拿到監(jiān)聽里,所以你添加的屬性都會(huì)被獲得到。

cn.bugstack.springframework.test.event.CustomEventListener

  1. public class CustomEventListener implements ApplicationListener<CustomEvent> { 
  2.  
  3.     @Override 
  4.     public void onApplicationEvent(CustomEvent event) { 
  5.         System.out.println("收到:" + event.getSource() + "消息;時(shí)間:" + new Date()); 
  6.         System.out.println("消息:" + event.getId() + ":" + event.getMessage()); 
  7.     } 
  8.  
  • 這個(gè)是一個(gè)用于監(jiān)聽 CustomEvent 事件的監(jiān)聽器,這里你可以處理自己想要的操作,比如一些用戶注冊(cè)后發(fā)送優(yōu)惠券和短信通知等。
  • 另外是關(guān)于 ContextRefreshedEventListener implements ApplicationListener、ContextClosedEventListener implements ApplicationListener 監(jiān)聽器,這里就不演示了,可以參考下源碼。

2. 配置文件

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans> 
  3.  
  4.     <bean class="cn.bugstack.springframework.test.event.ContextRefreshedEventListener"/> 
  5.  
  6.     <bean class="cn.bugstack.springframework.test.event.CustomEventListener"/> 
  7.  
  8.     <bean class="cn.bugstack.springframework.test.event.ContextClosedEventListener"/> 
  9.  
  10. </beans> 

 

  • 在 spring.xml 中配置了三個(gè)事件監(jiān)聽器,監(jiān)聽刷新、監(jiān)控自定義事件、監(jiān)聽關(guān)閉事件。

3. 單元測試

  1. public class ApiTest { 
  2.  
  3.     @Test 
  4.     public void test_event() { 
  5.         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml"); 
  6.         applicationContext.publishEvent(new CustomEvent(applicationContext, 1019129009086763L, "成功了!")); 
  7.  
  8.         applicationContext.registerShutdownHook(); 
  9.     } 
  10.  
  • 通過使用 applicationContext 新增加的發(fā)布事件接口方法,發(fā)布一個(gè)自定義事件 CustomEvent,并透傳了相應(yīng)的參數(shù)信息。

測試結(jié)果

  1. 刷新事件:cn.bugstack.springframework.test.event.ContextRefreshedEventListener$$EnhancerByCGLIB$$440a36f5 
  2. 收到:cn.bugstack.springframework.context.support.ClassPathXmlApplicationContext@71c7db30消息;時(shí)間:22:32:50 
  3. 消息:1019129009086763:成功了! 
  4. 關(guān)閉事件:cn.bugstack.springframework.test.event.ContextClosedEventListener$$EnhancerByCGLIB$$f4d4b18d 
  5.  
  6. Process finished with exit code 0 
  • 從測試結(jié)果可以看到,我們自己定義的事件和監(jiān)聽,以及監(jiān)聽系統(tǒng)的事件信息,都可以在控制臺(tái)完整的輸出出來了。你也可以嘗試增加一些其他事件行為,并調(diào)試代碼學(xué)習(xí)觀察者模式。

六、總結(jié)

 

  • 在整個(gè)手寫 Spring 框架的學(xué)習(xí)過程中,可以逐步看到很多設(shè)計(jì)模式的使用,比如:簡單工廠BeanFactory、工廠方法FactoryBean、策略模式訪問資源,現(xiàn)在又實(shí)現(xiàn)了一個(gè)觀察者模式的具體使用。所以學(xué)習(xí) Spring 的過程中,要更加注意關(guān)于設(shè)計(jì)模式的運(yùn)用,這是你能讀懂代碼的核心也是學(xué)習(xí)的重點(diǎn)。
  • 那么本章節(jié)關(guān)于觀察者模式的實(shí)現(xiàn)過程,主要包括了事件的定義、事件的監(jiān)聽和發(fā)布事件,發(fā)布完成后根據(jù)匹配策略,監(jiān)聽器就會(huì)收到屬于自己的事件內(nèi)容,并做相應(yīng)的處理動(dòng)作,這樣的觀察者模式其實(shí)日常我們也經(jīng)常使用,不過在結(jié)合 Spring 以后,除了設(shè)計(jì)模式的學(xué)習(xí),還可以學(xué)到如何把相應(yīng)觀察者的實(shí)現(xiàn)和應(yīng)用上下文結(jié)合。
  • 所有在 Spring 學(xué)習(xí)到的技術(shù)、設(shè)計(jì)、思路都是可以和實(shí)際的業(yè)務(wù)開發(fā)結(jié)合起來的,而這些看似比較多的代碼模塊,其實(shí)也是按照各自職責(zé)一點(diǎn)點(diǎn)的擴(kuò)充進(jìn)去的。在自己的學(xué)習(xí)過程中,可以先動(dòng)手嘗試完成這些框架功能,在一點(diǎn)點(diǎn)通過調(diào)試的方式與 Spring 源碼進(jìn)行對(duì)照參考,最終也就慢慢掌握這些設(shè)計(jì)和編碼能力了。

 

責(zé)任編輯:武曉燕 來源: bugstack蟲洞棧
相關(guān)推薦

2021-06-07 20:03:04

監(jiān)聽器模式觀察者

2010-08-09 09:47:34

Flex事件機(jī)制

2025-05-20 07:13:22

Spring異步解耦Event

2022-11-15 07:35:50

Spring事件觀察者模式

2023-11-01 07:55:03

事件監(jiān)聽器傳遞數(shù)據(jù)

2009-06-22 09:23:18

事件監(jiān)聽器

2009-07-17 09:55:02

事件監(jiān)聽器SWT和SwingAWT

2020-12-15 10:46:29

事件監(jiān)聽器Spring Boot

2010-08-09 11:06:01

Flex事件機(jī)制

2012-02-03 13:27:16

2020-10-12 10:58:15

IDEA插件監(jiān)聽

2011-11-30 11:09:32

H3C網(wǎng)絡(luò)

2009-07-01 09:43:00

2023-11-01 08:22:07

Spring發(fā)布器源對(duì)象

2017-01-22 11:04:47

2024-06-04 13:11:52

Python行為設(shè)計(jì)模式開發(fā)

2020-10-26 08:45:39

觀察者模式

2021-09-06 10:04:47

觀察者模式應(yīng)用

2021-04-14 14:40:37

forSpringJava

2010-08-06 10:03:42

Flex事件
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 日日夜夜天天久久 | 亚洲精品在线观看网站 | 亚洲综合天堂 | 欧美日韩综合一区 | 97伊人| 四虎影院一区二区 | 请别相信他免费喜剧电影在线观看 | 美女艹b| www.9191| 翔田千里一区二区 | 毛片在线免费播放 | 国产欧美一区二区三区久久人妖 | 亚洲国产精品一区二区www | 蜜桃视频在线观看免费视频网站www | 91在线视频观看免费 | h片在线观看网站 | 午夜久久 | 成人精品一区二区三区 | 成人免费观看视频 | 国产精品一区在线 | 欧美在线视频网 | 97视频在线观看网站 | 精品99在线 | 亚洲精品第一国产综合野 | 一区二区视频在线 | www.色.com | 奇米久久久 | 日本久久久久久 | 操夜夜| 欧美成人一区二免费视频软件 | 国产一区二区三区不卡av | 999久久久国产精品 欧美成人h版在线观看 | 一区二区三区国产精品 | 男女激情网| 免费午夜电影 | 日韩免费网站 | 中文字幕乱码视频32 | 免费看黄色视屏 | 国产一级视频在线 | 先锋资源在线 | 国产精品美女久久久久aⅴ国产馆 |