2019独角兽企业重金招聘Python工程师标准>>>
说在前面
本文转自“天河聊技术”微信公众号
spring事件驱动模型发布事件。
正文
找到这个方法
org.springframework.context.event.GenericApplicationListenerAdapter#onApplicationEvent
跟到这个方法
org.springframework.context.event.ApplicationListenerMethodAdapter#onApplicationEvent
@Override public void onApplicationEvent(ApplicationEvent event) { processEvent(event); }
进入这个方法
public void processEvent(ApplicationEvent event) { Object[] args = resolveArguments(event); if (shouldHandle(event, args)) { // 执行事件监听器 Object result = doInvoke(args); if (result != null) { // 发布事件 handleResult(result); } else { logger.trace("No result object given - no result to handle"); } } }
进入这个方法
protected void handleResult(Object result) { if (result.getClass().isArray()) { Object[] events = ObjectUtils.toObjectArray(result); for (Object event : events) { // 发布事件 publishEvent(event); } } else if (result instanceof Collection>) { Collection> events = (Collection>) result; for (Object event : events) { publishEvent(event); } } else { publishEvent(result); } }
进入这个方法
org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object)
@Override public void publishEvent(Object event) { publishEvent(event, null); }
跟踪发布事件的方法
protected void publishEvent(Object event, @Nullable ResolvableType eventType) { Assert.notNull(event, "Event must not be null"); if (logger.isTraceEnabled()) { logger.trace("Publishing event in " + getDisplayName() + ": " + event); } // Decorate event as an ApplicationEvent if necessary ApplicationEvent applicationEvent; if (event instanceof ApplicationEvent) { applicationEvent = (ApplicationEvent) event; } else { applicationEvent = new PayloadApplicationEvent<>(this, event); if (eventType == null) { eventType = ((PayloadApplicationEvent) applicationEvent).getResolvableType(); } } // Multicast right now if possible - or lazily once the multicaster is initialized if (this.earlyApplicationEvents != null) { this.earlyApplicationEvents.add(applicationEvent); } else { // 广播事件 getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); } // Publish event via parent context as well... if (this.parent != null) { if (this.parent instanceof AbstractApplicationContext) { ((AbstractApplicationContext) this.parent).publishEvent(event, eventType); } else { this.parent.publishEvent(event); } } }
跟踪这一行
else { // 广播事件 getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); }
进入这个方法
org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)
@Override public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); // 获取监听器 for (final ApplicationListener> listener : getApplicationListeners(event, type)) { Executor executor = getTaskExecutor(); if (executor != null) { // 执行事件监听器 executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } } }
进入这一行代码
// 获取监听器 for (final ApplicationListener> listener : getApplicationListeners(event, type)) {
//获取事件监听器集合 protected Collection> getApplicationListeners( ApplicationEvent event, ResolvableType eventType) { Object source = event.getSource(); Class> sourceType = (source != null ? source.getClass() : null); // 获得事件监听器的缓存key ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType); // Quick check for existing entry on ConcurrentHashMap... // 从缓存中获取监听器的筛选器 ListenerRetriever retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { // 获取事件监听器 return retriever.getApplicationListeners(); } if (this.beanClassLoader == null || (ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) && (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) { // Fully synchronized building and caching of a ListenerRetriever synchronized (this.retrievalMutex) { retriever = this.retrieverCache.get(cacheKey); if (retriever != null) { return retriever.getApplicationListeners(); } retriever = new ListenerRetriever(true); Collection > listeners = retrieveApplicationListeners(eventType, sourceType, retriever); this.retrieverCache.put(cacheKey, retriever); return listeners; } } else { // No ListenerRetriever caching -> no synchronization necessary return retrieveApplicationListeners(eventType, sourceType, null); } }
跟踪到这里
if (retriever != null) { // 获取事件监听器 return retriever.getApplicationListeners(); }
// 从beanFactory中获取事件监听器对象 public Collection> getApplicationListeners() { LinkedList > allListeners = new LinkedList<>(); for (ApplicationListener> listener : this.applicationListeners) { allListeners.add(listener); } if (!this.applicationListenerBeans.isEmpty()) { BeanFactory beanFactory = getBeanFactory(); for (String listenerBeanName : this.applicationListenerBeans) { try { // 从beanFactory中获取事件监听器对象 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 } } } // 给监听器排序 AnnotationAwareOrderComparator.sort(allListeners); return allListeners; } }
返回到这个方法
org.springframework.context.event.AbstractApplicationEventMulticaster#getApplicationListeners(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)
这一行代码
Collection> listeners = retrieveApplicationListeners(eventType, sourceType, retriever);
从beanFactory中获取事件监听器对象
private Collection> retrieveApplicationListeners( ResolvableType eventType, @Nullable Class> sourceType, @Nullable ListenerRetriever retriever) { LinkedList > allListeners = new LinkedList<>(); Set > listeners; Set listenerBeans; synchronized (this.retrievalMutex) { listeners = new LinkedHashSet<>(this.defaultRetriever.applicationListeners); listenerBeans = new LinkedHashSet<>(this.defaultRetriever.applicationListenerBeans); } for (ApplicationListener> listener : listeners) { if (supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListeners.add(listener); } allListeners.add(listener); } } if (!listenerBeans.isEmpty()) { BeanFactory beanFactory = getBeanFactory(); for (String listenerBeanName : listenerBeans) { try { Class> listenerType = beanFactory.getType(listenerBeanName); if (listenerType == null || supportsEvent(listenerType, eventType)) { ApplicationListener> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class); if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) { if (retriever != null) { retriever.applicationListenerBeans.add(listenerBeanName); } allListeners.add(listener); } } } catch (NoSuchBeanDefinitionException ex) { // Singleton listener instance (without backing bean definition) disappeared - // probably in the middle of the destruction phase } } } AnnotationAwareOrderComparator.sort(allListeners); return allListeners; }
返回到这个方法
org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)
这行代码
if (executor != null) { // 执行事件监听器 executor.execute(() -> 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); } }
说到最后
到这里结束了,仅供参考。