Spring 5 SimpleApplicationEventMulticaster 源码分析

SimpleApplicationEventMulticaster

SimpleApplicationEventMulticaster 是 AbstractApplicationContext 的默认事件多播器

/**
 * Simple implementation of the {@link ApplicationEventMulticaster} interface.
 * <p>简单实现的 ApplicationEventMulticaster 接口</p>
 * <p>Multicasts all events to all registered listeners, leaving it up to
 * the listeners to ignore events that they are not interested in.
 * Listeners will usually perform corresponding {@code instanceof}
 * checks on the passed-in event object.
 * <p>将所有事件多播给所有注册的监听器,让监听器忽略它们不感兴趣的事件。监听器通常
 * 会对传入的事件对象执行相应的 instanceof 检查</p>
 * <p>多播:一点对多点的通信</p>
 *
 * <p>By default, all listeners are invoked in the calling thread.
 * This allows the danger of a rogue listener blocking the entire application,
 * but adds minimal overhead. Specify an alternative task executor to have
 * listeners executed in different threads, for example from a thread pool.
 * <p>默认情况下,所有监听器都在调用线程中调用。这允许恶意监听器阻塞整个应用程序的
 * 危险,但只增加最小的开销。指定另一个任务执行器,让监听器在不同的线程中执行,例如
 * 从线程池中执行</p>
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Stephane Nicoll
 * @see #setTaskExecutor
 */
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
    
    

	/**
	 * 当前任务线程池
	 */
	@Nullable
	private Executor taskExecutor;

	@Nullable
	private ErrorHandler errorHandler;


	/**
	 * Create a new SimpleApplicationEventMulticaster.
	 * <p>创建一个新的 SimpleApplicationEventMulticaster </p>
	 */
	public SimpleApplicationEventMulticaster() {
    
    
	}

	/**
	 * Create a new SimpleApplicationEventMulticaster for the given BeanFactory.
	 * <p>为给定的BeanFactory创建一个新的 SimpleApplicationEventMulticaster </p>
	 */
	public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
    
    
		setBeanFactory(beanFactory);
	}


	/**
	 * Set a custom executor (typically a {@link org.springframework.core.task.TaskExecutor})
	 * to invoke each listener with.
	 * <p>Default is equivalent to {@link org.springframework.core.task.SyncTaskExecutor},
	 * executing all listeners synchronously in the calling thread.
	 * <p>Consider specifying an asynchronous task executor here to not block the
	 * caller until all listeners have been executed. However, note that asynchronous
	 * execution will not participate in the caller's thread context (class loader,
	 * transaction association) unless the TaskExecutor explicitly supports this.
	 * @see org.springframework.core.task.SyncTaskExecutor
	 * @see org.springframework.core.task.SimpleAsyncTaskExecutor
	 */
	public void setTaskExecutor(@Nullable Executor taskExecutor) {
    
    
		this.taskExecutor = taskExecutor;
	}

	/**
	 * Return the current task executor for this multicaster.
	 * <p>返回此多播器的当前任务线程池</p>
	 */
	@Nullable
	protected Executor getTaskExecutor() {
    
    
		return this.taskExecutor;
	}

	/**
	 * Set the {@link ErrorHandler} to invoke in case an exception is thrown
	 * from a listener.
	 * <p>Default is none, with a listener exception stopping the current
	 * multicast and getting propagated to the publisher of the current event.
	 * If a {@linkplain #setTaskExecutor task executor} is specified, each
	 * individual listener exception will get propagated to the executor but
	 * won't necessarily stop execution of other listeners.
	 * <p>Consider setting an {@link ErrorHandler} implementation that catches
	 * and logs exceptions (a la
	 * {@link org.springframework.scheduling.support.TaskUtils#LOG_AND_SUPPRESS_ERROR_HANDLER})
	 * or an implementation that logs exceptions while nevertheless propagating them
	 * (e.g. {@link org.springframework.scheduling.support.TaskUtils#LOG_AND_PROPAGATE_ERROR_HANDLER}).
	 * @since 4.1
	 */
	public void setErrorHandler(@Nullable ErrorHandler errorHandler) {
    
    
		this.errorHandler = errorHandler;
	}

	/**
	 * Return the current error handler for this multicaster.
	 * <p>返回此多播器的当前错误处理程序</p>
	 * @since 4.1
	 */
	@Nullable
	protected ErrorHandler getErrorHandler() {
    
    
		return this.errorHandler;
	}


	@Override
	public void multicastEvent(ApplicationEvent event) {
    
    
		multicastEvent(event, resolveDefaultEventType(event));
	}

	@Override
	public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
    
    
		//如果 eventType 不为null 就引用 eventType ;否则 将 event 转换为 ResolvableType 对象 再引用
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		//获取此多播器的当前任务线程池
		Executor executor = getTaskExecutor();
		//遍历 获取所有支持event的监听器
		for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
    
    
			//如果 executor 不为 null
			if (executor != null) {
    
    
				//使用executor 回调listener的onApplicationEvent方法,传入 event
				executor.execute(() -> invokeListener(listener, event));
			}
			else {
    
    
				//回调listener的onApplicationEvent方法,传入 event
				invokeListener(listener, event);
			}
		}
	}

	/**
	 * 将 event 转换为 ResolvableType 对象
	 * @param event 事件对象
	 */
	private ResolvableType resolveDefaultEventType(ApplicationEvent event) {
    
    
		return ResolvableType.forInstance(event);
	}

	/**
	 * <p>回调listener的onApplicationEvent方法,传入 event</p>
	 * Invoke the given listener with the given event.
	 * <p>使用给定的事件调用给定的监听器</p>
	 * @param listener the ApplicationListener to invoke
	 *                 -- 要调用的ApplicationListenere
	 * @param event the current event to propagate
	 *              -- 要传播的当前事件
	 * @since 4.1
	 */
	protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
    
    
		//获取此多播器的当前错误处理程序
		ErrorHandler errorHandler = getErrorHandler();
		//如果 errorHandler 不为 null
		if (errorHandler != null) {
    
    
			try {
    
    
				//回调listener的onApplicationEvent方法,传入 event
				doInvokeListener(listener, event);
			}
			catch (Throwable err) {
    
    
				//交给errorHandler接收处理 err
				errorHandler.handleError(err);
			}
		}
		else {
    
    
			//回调listener的onApplicationEvent方法,传入 event
			doInvokeListener(listener, event);
		}
	}

	/**
	 * 回调listener的onApplicationEvent方法,传入 event
	 * @param listener 监听器对象
	 * @param event 事件对象
	 */
	@SuppressWarnings({
    
    "rawtypes", "unchecked"})
	private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
    
    
		try {
    
    
			//回调listener的onApplicationEvent方法,传入 event
			listener.onApplicationEvent(event);
		}
		catch (ClassCastException ex) {
    
    //捕捉类转换异常
			//获取异常信息
			String msg = ex.getMessage();
			//如果meg为null || 匹配类转换消息,以保证抛出类转换异常是因eventClass引起的
			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.
				// 可能是 lambda定义的监听器,我们无法解析的通用事件类型 -> 让我们抑制异常,只记录一条调试信息
				Log logger = LogFactory.getLog(getClass());
				//如果当前日志是跟踪级别
				if (logger.isTraceEnabled()) {
    
    
					//打印跟踪日志:监听器的无法匹配事件类型
					logger.trace("Non-matching event type for listener: " + listener, ex);
				}
			}
			else {
    
    
				//抛出异常
				throw ex;
			}
		}
	}

	/**
	 * 匹配类转换消息,以保证抛出类转换异常是因eventClass引起的
	 * @param classCastMessage 类转换异常消息
	 * @param eventClass 事件类型
	 */
	private boolean matchesClassCastMessage(String classCastMessage, Class<?> eventClass) {
    
    
		// On Java 8, the message starts with the class name: "java.lang.String cannot be cast..."
		// 在 JAVA 8中,消息以类名开始:'java.lang.String 不能被转换 .. '
		//如果 classCastMessage 是以 eventClass类名开头,返回true
		if (classCastMessage.startsWith(eventClass.getName())) {
    
    
			//返回true
			return true;
		}
		// On Java 11, the message starts with "class ..." a.k.a. Class.toString()
		// 在 JAVA 11 中,消息是以'class ...' 开始,选择 Class.toString
		//如果 classCastMessage是以 eventClass.toString()开头,返回true
		if (classCastMessage.startsWith(eventClass.toString())) {
    
    
			//返回true
			return true;
		}
		// On Java 9, the message used to contain the module name: "java.base/java.lang.String cannot be cast..."
		// 在 Java 9, 用于包含模块名的消息:'java.base/java.lang.String 不能被转换'
		// 找出 classCastMessage 的 '/' 第一个索引位置
		int moduleSeparatorIndex = classCastMessage.indexOf('/');
		//如果找到了'/'位置 && '/'后面的字符串是以eventClass类名开头
		if (moduleSeparatorIndex != -1 && classCastMessage.startsWith(eventClass.getName(), moduleSeparatorIndex + 1)) {
    
    
			//返回true
			return true;
		}
		// Assuming an unrelated class cast failure...
		// 假设一个不相关的类转换失败
		//返回false
		return false;
	}

}

AbstractApplicationEventMulticaster

/**
 * Abstract implementation of the {@link ApplicationEventMulticaster} interface,
 * providing the basic listener registration facility.
 * <p>抽线实现了 ApplicationEventMulticaster 接口,提供了基础的监听器注册工具</p>
 * <p>Doesn't permit multiple instances of the same listener by default,
 * as it keeps listeners in a linked Set. The collection class used to hold
 * ApplicationListener objects can be overridden through the "collectionClass"
 * bean property.
 * <p>默认情况下不允许同一个监听器由多个实例,因为它将监听器保持在一个链接的集合张</p>
 *
 * <p>Implementing ApplicationEventMulticaster's actual {@link #multicastEvent} method
 * is left to subclasses. {@link SimpleApplicationEventMulticaster} simply multicasts
 * all events to all registered listeners, invoking them in the calling thread.
 * Alternative implementations could be more sophisticated in those respects.
 * <p>实现 ApplicationEventMulticaster 的实际的 mulicastEvent 方法留给子类。
 * SimpleApplicationEventMuliticaster 简单地将所有事件多播给所有注册的监听器,在
 * 调用线程中调用它们。这些方面,可选实现可能更复杂。</p>
 *
 * @author Juergen Hoeller
 * @author Stephane Nicoll
 * @since 1.2.3
 * @see #getApplicationListeners(ApplicationEvent, ResolvableType)
 * @see SimpleApplicationEventMulticaster
 */
public abstract class AbstractApplicationEventMulticaster
		implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware {
    
    

	/**
	 * 默认的存放多个ApplicationListener对象容器。保存者所有监听器
	 */
	private final ListenerRetriever defaultRetriever = new ListenerRetriever(false);

	/**
	 * 缓存Map Key=事件类型和源类型 ,value= 存放多个ApplicationListener对象容器
	 */
	final Map<ListenerCacheKey, ListenerRetriever> retrieverCache = new ConcurrentHashMap<>(64);

	@Nullable
	private ClassLoader beanClassLoader;

	/**
	 * 当前BeanFactory
	 */
	@Nullable
	private ConfigurableBeanFactory beanFactory;

	/**
	 * 互斥锁
	 */
	private Object retrievalMutex = this.defaultRetriever;


	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
    
    
		this.beanClassLoader = classLoader;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
    
    
		//如果 beanFactory 不是 ConfigurableBeanFactory 实例
		if (!(beanFactory instanceof ConfigurableBeanFactory)) {
    
    
			// 抛出非法状态异常:不在 ConfigurableBeanFactory:beanFactory
			throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
		}
		this.beanFactory = (ConfigurableBeanFactory) beanFactory;
		//如果 beanClassLoader 为 null
		if (this.beanClassLoader == null) {
    
    
			//获取beanFactory的类加载器以加载Bean类(即使无法使用系统ClassLoader,也只能为null)
			this.beanClassLoader = this.beanFactory.getBeanClassLoader();
		}
		//获取beanFactory使用的单例互斥锁(用于外部协作者)
		this.retrievalMutex = this.beanFactory.getSingletonMutex();
	}

	/**
	 * 获取当前BeanFactory
	 * @return
	 */
	private ConfigurableBeanFactory getBeanFactory() {
    
    
		//如果 beanFactory 为 null
		if (this.beanFactory == null) {
    
    
			//抛出非法状态异常:ApplicationEventMulticaster不能检索监听器Bean,因为它与BeanFactory没有关联
			throw new IllegalStateException("ApplicationEventMulticaster cannot retrieve listener beans " +
					"because it is not associated with a BeanFactory");
		}
		//返回当前BeanFactory
		return this.beanFactory;
	}


	@Override
	public void addApplicationListener(ApplicationListener<?> listener) {
    
    
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			// Explicitly remove target for a proxy, if registered already,
			// in order to avoid double invocations of the same listener.
			// 显示删除代理的目标(如果已经注册),以避免对同一个监听器的两次调用
			//获取listener背后的singleton目标对象
			Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
			//如果 singletonTarget 是 ApplicationListener 实例
			if (singletonTarget instanceof ApplicationListener) {
    
    
				//将 singletonTarget 从 defaultRetriever.applicationListeners 中移除
				this.defaultRetriever.applicationListeners.remove(singletonTarget);
			}
			//将listener添加到 defaultRetriever.applicationListeners 中
			this.defaultRetriever.applicationListeners.add(listener);
			//清空缓存,因为 listener 可能支持缓存的某些事件类型和源类型 ,所以要刷新缓存
			this.retrieverCache.clear();
		}
	}

	@Override
	public void addApplicationListenerBean(String listenerBeanName) {
    
    
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			//将 listenerBeanName 添加到 defaultRetriever的applicationListenerBeans
			this.defaultRetriever.applicationListenerBeans.add(listenerBeanName);
			//清空缓存,因为 listener 可能支持缓存的某些事件类型和源类型 ,所以要刷新缓存
			this.retrieverCache.clear();
		}
	}

	@Override
	public void removeApplicationListener(ApplicationListener<?> listener) {
    
    
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			//将 listener 从 retriever的ApplicationListener 对象集合中 移除
			this.defaultRetriever.applicationListeners.remove(listener);
			//清空缓存,因为 listener 可能支持缓存的某些事件类型和源类型 ,所以要刷新缓存
			this.retrieverCache.clear();
		}
	}

	@Override
	public void removeApplicationListenerBean(String listenerBeanName) {
    
    
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			//将 listener 从 retriever的ApplicationListener 对象集合中 移除
			this.defaultRetriever.applicationListenerBeans.remove(listenerBeanName);
			//清空缓存,因为 listener 可能支持缓存的某些事件类型和源类型 ,所以要刷新缓存
			this.retrieverCache.clear();
		}
	}

	@Override
	public void removeAllListeners() {
    
    
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			//清空 defaultRetriever 的ApplicationListener 对象集合
			this.defaultRetriever.applicationListeners.clear();
			//清空 defaultRetriever 的 BeanFactory中的 applicationListener 类型 Bean名 集合
			this.defaultRetriever.applicationListenerBeans.clear();
			//清空缓存,因为 listener 可能支持缓存的某些事件类型和源类型 ,所以要刷新缓存
			this.retrieverCache.clear();
		}
	}


	/**
	 * Return a Collection containing all ApplicationListeners.
	 * <p>返回包含所有 applicationListenere 的集合</p>
	 * @return a Collection of ApplicationListeners
	 * 		-- applicationListenere集合
	 * @see org.springframework.context.ApplicationListener
	 */
	protected Collection<ApplicationListener<?>> getApplicationListeners() {
    
    
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			//返回 defaultRetriever 的包含所有 applicationListenere 的集合
			return this.defaultRetriever.getApplicationListeners();
		}
	}

	/**
	 * <p>获取所有支持event的监听器</p>
	 * Return a Collection of ApplicationListeners matching the given
	 * event type. Non-matching listeners get excluded early.
	 * <p>返回给定事件类型匹配的 applicationListenere 集合。不匹配的监听器
	 * 很早就排除在外</p>
	 * @param event the event to be propagated. Allows for excluding
	 * non-matching listeners early, based on cached matching information.
	 *              -- 要传播的事件。允许根据缓存的匹配信息及早排除不匹配的监听器
	 * @param eventType the event type
	 *                  	-- 事件类型
	 * @return a Collection of ApplicationListeners
	 * 	-- ApplicationListener集
	 * @see org.springframework.context.ApplicationListener
	 */
	protected Collection<ApplicationListener<?>> getApplicationListeners(
			ApplicationEvent event, ResolvableType eventType) {
    
    
		//event.getSource:事件最初在其上发生的对象。
		//获取event最初在其上发生的对象
		Object source = event.getSource();
		//如果source不为nul就获取source的Class对象;否则引用null
		Class<?> sourceType = (source != null ? source.getClass() : null);
		//根据 eventType和 sourceType 新建一个 ListenerRetievers 缓存键
		ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);

		// Quick check for existing entry on ConcurrentHashMap...
		// 在 ConcurrentHashMap 上快速检查现有条目
		// 从retrieverCache中获取 cacheKey 对应的 ListenerRetriever对象
		ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
		//如果 retriever 不为 null
		if (retriever != null) {
    
    
			//获取 ListenerRetriever 存放的所有 ApplicationListener 对象
			return retriever.getApplicationListeners();
		}

		//ClassUtils.isCacheSafe(Class<?> clazz,@Nullable ClassLoader classLoader):检查给定的类对象在给定的上下文中是否缓
		// 	存安全,即判断是否由 给定的类加载器或者给定的类加载的父级类加载器加载过
		//如果 beanClassLoader 为null || (event的Class对象已经被 beanClassLoader 加载过 && (sourceType 为 null ||
		// 	sourceType已经被 beanClassLoader 加载过))
		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
			// ListenerRetriever 完全同步的构建和缓存
			// 使用 retrievalMutex 加锁保证线程安全
			synchronized (this.retrievalMutex) {
    
    
				//从retrieverCache中获取 cacheKey 对应的 ListenerRetriever对象
				retriever = this.retrieverCache.get(cacheKey);
				//如果 retriever 不为 null
				if (retriever != null) {
    
    
					//获取 ListenerRetriever 存放的所有 ApplicationListener 对象
					return retriever.getApplicationListeners();
				}
				//新建一个 ListenerRetriever 对象
				retriever = new ListenerRetriever(true);
				//过滤出所有支持eventType以及sourceType的ApplicationListener对象的列表
				Collection<ApplicationListener<?>> listeners =
						retrieveApplicationListeners(eventType, sourceType, retriever);
				//将 cacheKey,retriever 绑定到 retrieverCache中
				this.retrieverCache.put(cacheKey, retriever);
				//返回 listeners
				return listeners;
			}
		}
		else {
    
    
			// No ListenerRetriever caching -> no synchronization necessary
			// 没有 ListenerRetriever 缓存 -> 不需要同步
			//过滤出所有支持eventType以及sourceType的ApplicationListener对象的列表,不使用缓存
			return retrieveApplicationListeners(eventType, sourceType, null);
		}
	}

	/**
	 * <p>过滤出所有支持eventType以及sourceType的ApplicationListener对象的列表</p>
	 * Actually retrieve the application listeners for the given event and source type.
	 * <p>实际检索 给定事件 和原类型的应用程序监听器</p>
	 * @param eventType the event type -- 事件类型
	 * @param sourceType the event source type -- 事件源类型
	 * @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes)
	 *                  -- ListenerRetriever,如果假设填充一个(用于缓存目的)
	 * @return the pre-filtered list of application listeners for the given event and source type
	 * 	-- 针对给定事件和原类型预筛选的应用程序监听器列表
	 */
	private Collection<ApplicationListener<?>> retrieveApplicationListeners(
			ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable ListenerRetriever retriever) {
    
    
		//存放所有支持eventType以及sourceType的ApplicationListener 对象 的列表
		List<ApplicationListener<?>> allListeners = new ArrayList<>();
		Set<ApplicationListener<?>> listeners;
		Set<String> listenerBeans;
		//使用 retrievalMutex 加锁,保证线程安全
		synchronized (this.retrievalMutex) {
    
    
			//初始化  编程方式添加的静态 ApplicationListener 对象集合
			listeners = new LinkedHashSet<>(this.defaultRetriever.applicationListeners);
			// 初始化 BeanFactory中的 applicationListener 类型 Bean名 集合
			listenerBeans = new LinkedHashSet<>(this.defaultRetriever.applicationListenerBeans);
		}

		// Add programmatically registered listeners, including ones coming
		// from ApplicationListenerDetector (singleton beans and inner beans).
		// 添加以编程方式注册的监听器,包括来自 ApplicationListenerDeteor(单例Bean和内部Bean)的监听器
		// 遍历listeners
		for (ApplicationListener<?> listener : listeners) {
    
    
			//如果 listener 支持 eventType 事件类型以及 sourceType 源类型
			if (supportsEvent(listener, eventType, sourceType)) {
    
    
				//如果 retriever 不为null
				if (retriever != null) {
    
    
					//将 listener添加到 retriever的ApplicationListener 对象集合中
					retriever.applicationListeners.add(listener);
				}
				//将 listener添加到 allListeners 中
				allListeners.add(listener);
			}
		}

		// Add listeners by bean name, potentially overlapping with programmatically
		// registered listeners above - but here potentially with additional metadata.
		// 按Bean名称添加监听器,可能与编程方式重叠————但这里可能有额外的元数据
		// 如果listenerBean不是空集
		if (!listenerBeans.isEmpty()) {
    
    
			//获取当前BeanFactory
			ConfigurableBeanFactory beanFactory = getBeanFactory();
			//遍历 listenerBeans
			for (String listenerBeanName : listenerBeans) {
    
    
				try {
    
    
					//如果通过在尝试实例化listenerBeanName的BeanDefinition的监听器之前检查到 其泛型声明的事件类型支持 eventType
					if (supportsEvent(beanFactory, listenerBeanName, eventType)) {
    
    
						//从beanFactory中获取名为 listenerBeanName 的 ApplicationListener 类型的Bean对象
						ApplicationListener<?> listener =
								beanFactory.getBean(listenerBeanName, ApplicationListener.class);
						//如果 allListeners不包含 listener &&  listener 支持 eventType 事件类型以及 sourceType 源类型
						if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
    
    
							//如果 retriever 不为null
							if (retriever != null) {
    
    
								//如果 listenerBeanName 在 beanFactory中的Bean对象是单例
								if (beanFactory.isSingleton(listenerBeanName)) {
    
    
									//将 listener添加到 retriever的ApplicationListener 对象集合中
									retriever.applicationListeners.add(listener);
								}
								else {
    
    
									//将 listener添加到 allListeners 中
									retriever.applicationListenerBeans.add(listenerBeanName);
								}
							}
							//将 listener添加到 allListeners 中
							allListeners.add(listener);
						}
					}
					else {
    
    
						// Remove non-matching listeners that originally came from
						// ApplicationListenerDetector, possibly ruled out by additional
						// BeanDefinition metadata (e.g. factory method generics) above.
						// 删除最初来自 ApplicationListenerDetector 的不匹配监听器,可能被上面附加的 BeanDefinition元数据
						// (例如工厂方法泛型) 排除
						// 获取 在 beanFactory 中  listenerBeanName 的 Bean对象
						Object listener = beanFactory.getSingleton(listenerBeanName);
						//retriever不为null
						if (retriever != null) {
    
    
							//将 listener 从 retriever的ApplicationListener 对象集合中 移除
							retriever.applicationListeners.remove(listener);
						}
						//将 listener 从 allListeners 移除
						allListeners.remove(listener);
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
    
    // 没有这样的BeanDefinition异常
					// Singleton listener instance (without backing bean definition) disappeared -
					// probably in the middle of the destruction phase
					// 单例监听器实例(没有支持BeanDefinition)消失了————可能在销毁阶段的中间
				}
			}
		}
		//AnnotationAwareOrderComparator:OrderComparator的扩展,它支持Spring 的org.springframework.core.Ordered接口以及@Oreder和@Priority注解,
		// 	其中 Ordered实例提供的Order值将覆盖静态定义的注解值(如果有)
		//使用 AnnotationAwareOrderComparator 对 allListeners 进行排序
		AnnotationAwareOrderComparator.sort(allListeners);
		//如果 retriever 不为null && retriever的applicationListenerBeans是空集
		if (retriever != null && retriever.applicationListenerBeans.isEmpty()) {
    
    
			//将 retriever的 applicationListeners 的元素情空
			retriever.applicationListeners.clear();
			//将allListeners添加到  retriever的 applicationListeners
			retriever.applicationListeners.addAll(allListeners);
		}
		//返回 allListeners
		return allListeners;
	}

	/**
	 * <p>通过在尝试实例化listenerBeanName的BeanDefinition的监听器之前检查其泛型声明的事件类型是否支持 eventType </p>
	 * Filter a bean-defined listener early through checking its generically declared
	 * event type before trying to instantiate it.
	 * <p>通过在尝试实例化BeanDefinition的监听器之前检查其通用声明的事件类型,尽早筛选监听器</p>
	 * <p>If this method returns {@code true} for a given listener as a first pass,
	 * the listener instance will get retrieved and fully evaluated through a
	 * {@link #supportsEvent(ApplicationListener, ResolvableType, Class)} call afterwards.
	 * <p>如果该方法子啊第一次传递时对给定的监听器返回true,则随后将通过
	 * supportsEvent(ApplicationListener, ResolvableType, Class) 调用检索并全面评估监听器实例</p>
	 * @param beanFactory the BeanFactory that contains the listener beans
	 *                    	-- 包含监听器Bean的BeanFactory
	 * @param listenerBeanName the name of the bean in the BeanFactory
	 *                         -- 在 BeanFactory 中的Bean名
	 * @param eventType the event type to check
	 *                  -- 要检查的事件类型
	 * @return whether the given listener should be included in the candidates
	 * for the given event type
	 * 	-- 给定的监听器是否应包含在给定事件类型的候选中
	 * @see #supportsEvent(Class, ResolvableType)
	 * @see #supportsEvent(ApplicationListener, ResolvableType, Class)
	 */
	private boolean supportsEvent(
			ConfigurableBeanFactory beanFactory, String listenerBeanName, ResolvableType eventType) {
    
    
		//获取 listenerBeanName 在 beanFactory 中的 Class对象
		Class<?> listenerType = beanFactory.getType(listenerBeanName);
		//GenericApplicationListener:标准 ApplicationListener 接口的扩展变体,公开更多的元数据,比如受支持的事件 和 源类型。
		//			在Spring Framework 4.2中,这个接口用通用事件类型的完全处理取代了基于类的SmartApplicationListener
		//SmartApplicationListener:标准ApplicationListener接口扩展变体,公开更多的元数据,比如受支持的事件和源类型。
		//			对于泛型事件类型的完全内省,可以考虑实现 GenericApplictionListener 接口
		//如果 listenerType为null || listenerType 是 GenericApplicationListener 的子类或本身 || listenerType
		// 是 SmartApplicationListener 子类或本身
		if (listenerType == null || GenericApplicationListener.class.isAssignableFrom(listenerType) ||
				SmartApplicationListener.class.isAssignableFrom(listenerType)) {
    
    
			//返回true
			return true;
		}
		//如果 listenerType 不支持 eventType 的事件对象
		if (!supportsEvent(listenerType, eventType)) {
    
    
			//返回false
			return false;
		}
		try {
    
    
			//从 beanFactory 中获取listenerBeanName的合并BeanDefinition,如有必要,将子bean定义与 其父级合并
			BeanDefinition bd = beanFactory.getMergedBeanDefinition(listenerBeanName);
			//获取bd指定的Bean类的ResolvableType对象,然后转换为ApplicationListener的ResolvableType,最后获取第一个泛型参数的ResolveableType
			ResolvableType genericEventType = bd.getResolvableType().as(ApplicationListener.class).getGeneric();
			//如果 genericEventType 是 ResolvableType.NONE || eventType 是 genericEventType 的子类或实现,就返回true;否则返回false
			return (genericEventType == ResolvableType.NONE || genericEventType.isAssignableFrom(eventType));
		}
		catch (NoSuchBeanDefinitionException ex) {
    
    //捕捉 没有这样BeanDefinition异常
			// Ignore - no need to check resolvable type for manually registered singleton
			// 忽略 —— 对于手动注册的单例,不需要检查可解析类型
			// 返回true
			return true;
		}
	}

	/**
	 * <p>检查 listenerType 是否支持 eventType 的事件对象</p>
	 * Filter a listener early through checking its generically declared event
	 * type before trying to instantiate it.
	 * <p>在尝试实例化监听器之前,通过检查其通用声明的事件类型,尽早筛选监听器</p>
	 * <p>If this method returns {@code true} for a given listener as a first pass,
	 * the listener instance will get retrieved and fully evaluated through a
	 * {@link #supportsEvent(ApplicationListener, ResolvableType, Class)} call afterwards.
	 * <p>如果该方法在第一次传递是对给定的监听器返回true,则随后将通过
	 * 	supportsEvent(ApplicationListener, ResolvableType, Class) 调用检索并全面评估监听器实例</p>
	 * @param listenerType the listener's type as determined by the BeanFactory
	 *                     -- 由BeanFactory确定的监听器的类型
	 * @param eventType the event type to check
	 *                  -- 要检查的事件类型
	 * @return whether the given listener should be included in the candidates
	 * for the given event type
	 * 	-- 给定的监听器是否应包含在给定事件类型的候选中
	 */
	protected boolean supportsEvent(Class<?> listenerType, ResolvableType eventType) {
    
    
		//解析listenerType声明的事件类型
		ResolvableType declaredEventType = GenericApplicationListenerAdapter.resolveDeclaredEventType(listenerType);
		//如果 declaredEventType 为 null || eventType 是 declaredEventType 的子类或本身
		return (declaredEventType == null || declaredEventType.isAssignableFrom(eventType));
	}

	/**
	 * <p>确定 listener 是否支持 eventType 事件类型以及  sourceType 源类型 </p>
	 * Determine whether the given listener supports the given event.
	 * <p>确定给定监听器是否支持给定事件</p>
	 * <p>The default implementation detects the {@link SmartApplicationListener}
	 * and {@link GenericApplicationListener} interfaces. In case of a standard
	 * {@link ApplicationListener}, a {@link GenericApplicationListenerAdapter}
	 * will be used to introspect the generically declared type of the target listener.
	 * <p>默认实现检测 SmartApplicationListener 和 GenericApplicationListener 接口。对于
	 * 标准的ApplicationListenere,将使用 GenereicApplicationAdapter来内检通用声明的</p>
	 * @param listener the target listener to check
	 *                 -- 要检查的目标监听器
	 * @param eventType the event type to check against
	 *                  -- 要检查的事件类型
	 * @param sourceType the source type to check against
	 *                   -- 要检查的 源类型【源类型是指产生 eventType 类型的对象的类】
	 * @return whether the given listener should be included in the candidates
	 * for the given event type
	 * 		-- 给定的监听器是否应该包含在给定事件类型的候选中
	 */
	protected boolean supportsEvent(
			ApplicationListener<?> listener, ResolvableType eventType, @Nullable Class<?> sourceType) {
    
    
		//如果listener是GenericApplicationListener实例,将将其强转为GenericApplicationListener对象,否则创建一个
		// 	GenericApplicationListenerAdapter 对象来封装listener作为 GenericApplicationListener 对象
		GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ?
				(GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener));
		//如果 smartListener 支持 eventType 事件类型 && smartListener 支持 sourceType 源类型【源类型是指产生 eventType 类型的对象的类】
		return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType));
	}


	/**
	 * Cache key for ListenerRetrievers, based on event type and source type.
	 * <p>根据 事件类型 和 源类型 为 ListenerRetievers 缓存键 </p>
	 */
	private static final class ListenerCacheKey implements Comparable<ListenerCacheKey> {
    
    

		private final ResolvableType eventType;

		@Nullable
		private final Class<?> sourceType;

		/**
		 * 根据 eventType和 sourceType 新建一个  ListenerRetievers 缓存键
		 * @param eventType 事件类型
		 * @param sourceType 源类型
		 */
		public ListenerCacheKey(ResolvableType eventType, @Nullable Class<?> sourceType) {
    
    
			//如果eventType为null,抛出异常
			Assert.notNull(eventType, "Event type must not be null");
			this.eventType = eventType;
			this.sourceType = sourceType;
		}

		@Override
		public boolean equals(@Nullable Object other) {
    
    
			//如果 other 与 this 是同一个对象
			if (this == other) {
    
    
				//返回true
				return true;
			}
			//如果 other 不是 ListenerCacheKey 的实例
			if (!(other instanceof ListenerCacheKey)) {
    
    
				// 返回 false
				return false;
			}
			//将 other 强转为 ListenerCacheKey 对象
			ListenerCacheKey otherKey = (ListenerCacheKey) other;
			//ObjectUtils.nullSafeEquals:确定给定的对象是否相等,如果两个都为null返回true ,如果其中一个为null,返回false
			//如果 eventType 与 otherKey.eventType 相同 &&  sourceType 与 otherKey.sourceType 相同 时,返回true;否则返回false
			return (this.eventType.equals(otherKey.eventType) &&
					ObjectUtils.nullSafeEquals(this.sourceType, otherKey.sourceType));
		}

		@Override
		public int hashCode() {
    
    
			return this.eventType.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.sourceType);
		}

		@Override
		public String toString() {
    
    
			return "ListenerCacheKey [eventType = " + this.eventType + ", sourceType = " + this.sourceType + "]";
		}

		@Override
		public int compareTo(ListenerCacheKey other) {
    
    
			// 获取比较 eventype 序列化成字符串 与 other.eventType序列化成字符串 的结果
			int result = this.eventType.toString().compareTo(other.eventType.toString());
			// 如果result为0时
			if (result == 0) {
    
    
				//如果 sourceType为null
				if (this.sourceType == null) {
    
    
					//如果 other.sourceType 为 null,返回 0;否则返回-1
					return (other.sourceType == null ? 0 : -1);
				}
				//如果 other.sourceType为null
				if (other.sourceType == null) {
    
    
					//返回 1
					return 1;
				}
				//获取比较 sourceType 类名 与 other.sourceType 类名 的结果
				result = this.sourceType.getName().compareTo(other.sourceType.getName());
			}
			return result;
		}
	}


	/**
	 * <p>存放多个ApplicationListener对象容器</p>
	 * Helper class that encapsulates a specific set of target listeners,
	 * allowing for efficient retrieval of pre-filtered listeners.
	 * <p>封装特定目标监听器的 Hellper 类,允许高效地检索预过滤的监听器</p>
	 * <p>An instance of this helper gets cached per event type and source type.
	 * <p>根据事件类型和源类型缓存此 helper 的实例</p>
	 */
	private class ListenerRetriever {
    
    

		/**
		 *  ApplicationListener 对象集合
		 */
		public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();

		/**
		 * BeanFactory中的 applicationListener 类型 Bean名 集合
		 */
		public final Set<String> applicationListenerBeans = new LinkedHashSet<>();

		/**
		 * 是否预过滤
		 */
		private final boolean preFiltered;

		/**
		 * 新建一个 ListenerRetriever 实例
		 * @param preFiltered 是否预过滤
		 */
		public ListenerRetriever(boolean preFiltered) {
    
    
			this.preFiltered = preFiltered;
		}

		/**
		 * 获取 ListenerRetriever 存放的所有 ApplicationListener 对象
		 * @return
		 */
		public Collection<ApplicationListener<?>> getApplicationListeners() {
    
    
			//定义存放所有监听器的集合
			List<ApplicationListener<?>> allListeners = new ArrayList<>(
					this.applicationListeners.size() + this.applicationListenerBeans.size());
			//将 applicationListeners 添加到 allListeners 中
			allListeners.addAll(this.applicationListeners);
			//如果 applicationListenerBeans 不是空集合
			if (!this.applicationListenerBeans.isEmpty()) {
    
    
				//获取当前上下文BeanFactory
				BeanFactory beanFactory = getBeanFactory();
				//遍历 applicationListenerBeans
				for (String listenerBeanName : this.applicationListenerBeans) {
    
    
					try {
    
    
						//从beanFactory中获取名为 listenerBeanName 的 ApplicationListener 类型的Bean对象
						ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
						//如果允许预过滤 || allListeneres没有包含该listener
						if (this.preFiltered || !allListeners.contains(listener)) {
    
    
							// 将 listener 添加 allListeners 中
							allListeners.add(listener);
						}
					}
					catch (NoSuchBeanDefinitionException ex) {
    
    //没有这样的BeanDefintion异常
						// Singleton listener instance (without backing bean definition) disappeared -
						// probably in the middle of the destruction phase
						// 单例监听器实例(没有支持 BeanDefinition)消失了————可能在销毁阶段中
					}
				}
			}
			//如果不允许预过滤 || applicationListenerBeans不是空集合
			if (!this.preFiltered || !this.applicationListenerBeans.isEmpty()) {
    
    
				//AnnotationAwareOrderComparator:OrderComparator的扩展,它支持Spring 的org.springframework.core.Ordered接口以及@Oreder和@Priority注解,
				// 	其中 Ordered实例提供的Order值将覆盖静态定义的注解值(如果有)
				//使用 AnnotationAwareOrderComparator 对 allListeners 进行排序
				AnnotationAwareOrderComparator.sort(allListeners);
			}
			return allListeners;
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_30321211/article/details/108326255