Spring ApplicationListener源碼解析
正文
對於ApplicationListener使用Spring的應該也熟悉,因為這就是我們平時學習的觀察者模式的實際代表。
Spring基於Java提供的EventListener實現瞭一套以Spring容器為基礎的觀察者模式的事件監聽功能,
用於隻要實現Spring提供的接口完成事件的定義和監聽者的定義,那麼就可以很快速的接入觀察者模式的實現。
ApplicationListener介紹
說ApplicationListener之前先要知道EventListener。
EventListener本身是一個接口,它的作用跟前面講到的Aware類似,都是隻定義最頂級的接口,並沒有實習對應的方法,並且該接口也是由JDK提供的,並不是直接由Spring提供,Spring隻是基於該接口實現瞭自己的一套事件監聽功能。
在Spring中實現事件監聽的接口是ApplicationListener,該接口繼承瞭EventListener,並做瞭對應的實現。
源碼如下:
package java.util; /** * A tagging interface that all event listener interfaces must extend. * @since JDK1.1 */ public interface EventListener { }
@FunctionalInterface public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { //監聽者監聽事件的邏輯處理 void onApplicationEvent(E event); static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) { return event -> consumer.accept(event.getPayload()); } }
ApplicationListener使用
對於ApplicationListener的使用,因為Spring已經做瞭自己的封裝,並且以Spring容器為基礎做瞭實現,那麼開發者使用時也可以很快的上手,隻要簡單的配置即可。
定義事件:
//事件繼承Spring中的ApplicationEvent public class MyEvent extends ApplicationEvent { private String name; public MyEvent(ApplicationContext source,String name) { super(source); this.name = name; } public String getName() { return name; } }
定義事件的監聽者
//定義監聽者實現ApplicationListener,並通過泛型聲明監聽的事件 @Component public class MyEventListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { System.out.println("監聽MyEvent:收到消息時間:"+event.getTimestamp()+"【消息name:"+event.getName() + "】"); } }
@Component public class MyEventProcessor implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public ApplicationContext getApplicationContext() { return applicationContext; } }
發佈事件
@SpringBootApplication public class BootApplication { @Resource private DefaultListableBeanFactory defaultListableBeanFactory; @Resource private MySpringAware mySpringAware; @Resource private MyEventProcessor myEventProcessor; public static void main(String[] args) { SpringApplication.run(BootApplication.class,args); } @PostConstruct public void init() { ApplicationContext applicationContext = myEventProcessor.getApplicationContext(); //發佈事件,事件發佈之後,前面訂閱的監聽者就會監聽到該事件發佈的消息 applicationContext.publishEvent(new MyEvent(applicationContext,"陳湯姆")); applicationContext.publishEvent(new MyEvent(applicationContext,"陳湯姆2")); } }
監聽者收到發佈的事件信息
ApplicationListener作用
從以上的例子中可以看到ApplicationListner的模式就是設計模式中的觀察者模式。
觀察者模式的作用很好的解決瞭同步交互的問題。
以發送者和接收者為例,接收者接收消息如果同步場景下需要與發送者實現同步調用,但是這樣就導致兩者之間無法解耦,而ApplicationListener就是解決同步的問題,ApplicationListener可以提供半解耦的方式實現兩者之間的交互,即發送者發送消息不需要與接收者之間實現同步通知,隻要訂閱發送者的事件即可完成雙發的交互。
這裡為什麼是半解耦,因為兩者之間還是有一定交互的,交互的點就在於發送者的發送方需要維護一個接收者的集合,發送方在發送時需要將具體的接收者放在集合中,在發送時通過遍歷集合發送給接收方,執行接收方的業務處理。
在ApplicationListener這個集合就是public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>(); 這個集合中就存儲瞭接收者的實例,最終會遍歷該集合執行接收者的業務邏輯。
這裡拋一個問題,其實ApplicationListener的功能通過MQ也可以實現,那麼觀察者模式和發佈訂閱模式的區別是什麼呢?歡迎評論區一起討論!
ApplicationListener註冊
對於ApplicationListener的註冊比較好梳理的,隻要找到存儲ApplicationListener的集合就可以知道怎麼add集合的。
在Spring中ApplicationListener的註冊也是在Spring中實現的。
具體的梳理邏輯如下:
org.springframework.context.support.AbstractApplicationContext#refresh
org.springframework.context.support.AbstractApplicationContext#registerListeners
org.springframework.context.event.AbstractApplicationEventMulticaster#addApplicationListener
源碼梳理如下:
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext { @Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); //註冊觀察者 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } } //將觀察者註入到集合中 protected void registerListeners() { // Register statically specified listeners first. for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { //調用集合的add操作 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { //獲取觀察者的集合 getApplicationEventMulticaster().multicastEvent(earlyEvent); } } } }
public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware { private class ListenerRetriever { //存儲觀察者的集合 public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>(); public final Set<String> applicationListenerBeans = new LinkedHashSet<>(); private final boolean preFiltered; public ListenerRetriever(boolean preFiltered) { this.preFiltered = preFiltered; } //獲取觀察者的集合 public Collection<ApplicationListener<?>> getApplicationListeners() { List<ApplicationListener<?>> allListeners = new ArrayList<>( this.applicationListeners.size() + this.applicationListenerBeans.size()); allListeners.addAll(this.applicationListeners); if (!this.applicationListenerBeans.isEmpty()) { BeanFactory beanFactory = getBeanFactory(); for (String listenerBeanName : this.applicationListenerBeans) { try { ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class); if (this.preFiltered || !allListeners.contains(listener)) { allListeners.add(listener); } } catch (NoSuchBeanDefinitionException ex) { // Singleton listener instance (without backing bean definition) disappeared - // probably in the middle of the destruction phase } } } if (!this.preFiltered || !this.applicationListenerBeans.isEmpty()) { AnnotationAwareOrderComparator.sort(allListeners); } return allListeners; } } }
從以上的源碼可以看到核心的集合就是applicationListeners。可以根據該集合梳理註冊和執行流程。
ApplicationListener執行
註冊梳理清晰,那麼執行自然也很好梳理瞭, 畢竟使用的都是同一個集合。
ApplicationListener的執行其實就是觀察者的執行,也就是在使用篇章中的MyEventListener,在MyEventListener中重寫瞭onApplicationEvent,其中實現瞭自己的邏輯,那麼執行就是將MyEventListener中重寫的方式如何在沒有同步調用的情況下執行。
執行的實現就是依賴觀察者的集合,在註冊中我們已經將所有的觀察者添加到瞭ApplicationListener集合中,隻要將該集合中的觀察者取出執行,即可完成半解耦的執行。
梳理流程如下:
org.springframework.context.ApplicationEventPublisher#publishEvent(org.springframework.context.ApplicationEvent)
org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType)
org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)
org.springframework.context.event.SimpleApplicationEventMulticaster#invokeListener
org.springframework.context.event.SimpleApplicationEventMulticaster#doInvokeListener
源碼如下:
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { @Override public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); //getApplicationListeners就是獲取ApplicationListener的集合 for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) { Executor executor = getTaskExecutor(); if (executor != null) { //執行監聽者的 executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } } } //執行監聽者邏輯 protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) { ErrorHandler errorHandler = getErrorHandler(); if (errorHandler != null) { try { doInvokeListener(listener, event); } catch (Throwable err) { errorHandler.handleError(err); } } else { doInvokeListener(listener, event); } } //最終執行邏輯 private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) { try { //調用監聽者重寫的onApplicationEvent方法 listener.onApplicationEvent(event); } catch (ClassCastException ex) { String msg = ex.getMessage(); if (msg == null || matchesClassCastMessage(msg, event.getClass())) { // Possibly a lambda-defined listener which we could not resolve the generic event type for // -> let's suppress the exception and just log a debug message. Log logger = LogFactory.getLog(getClass()); if (logger.isDebugEnabled()) { logger.debug("Non-matching event type for listener: " + listener, ex); } } else { throw ex; } } } }
總結
從以上的梳理中,對ApplicationListener的邏輯做一個總結,對於ApplicationListener整體邏輯梳理如下:
- 定義事件:MyEvent就是自定義的事件
- 定義監聽者:MyEventListener就是自定義的MyEvent的事件監聽者,隻要MyEvent事件被觸發,那麼MyEventListener就會自動執行
- 監聽者註冊:將MyEventListener註冊到ApplicationListener集合中
- 發佈事件:將自定的MyEvent發佈,發佈之後監聽者就會收到通知
- 讀取註冊的監聽者:將前面註冊到ApplicationListner集合的數據讀取
- 執行監聽者監聽邏輯:將讀取到的ApplicationListner集合執行MyEventListner的onApplicationEvent
以上就是自己關於Spring中ApplicationListener的理解,更多關於Spring ApplicationListener的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- springboot如何開啟一個監聽線程執行任務
- SpringBoot中ApplicationEvent和ApplicationListener用法小結
- 詳解Spring事件發佈與監聽機制
- java和Spring中觀察者模式的應用詳解
- SpringBoot事件發佈和監聽詳解