org.springframework.context.support.ApplicationListenerDetector 详细介绍

一,功能介绍

early post-processor for detecting inner beans as ApplicationListeners

早期的PostProcessor用来检测并处理内部(inner)bean作为 ApplicationListeners

BeanPostProcessor that detects beans which implement the ApplicationListener interface. This catches beans that can't reliably be detected by getBeanNamesForType and related operations which only work against top-level beans.

这个BeanPostProcessor 用于检测实现了 ApplicationListener 接口的 Bean,特别是那些无法通过 getBeanNamesForType 和相关操作检测到的内部 Bean,因为getBeanNamesForType 和相关操作 只针对 top-level beans。

言外之意就是这个 BeanPostProcessor 可以帮助你确保所有实现了 ApplicationListener 接口的 Bean 都能正确地处理应用事件,即使它们是内部 Bean 或非单例作用域的 Bean。

二,如何实现

java 复制代码
/**
 * {@code BeanPostProcessor} that detects beans which implement the {@code ApplicationListener}
 * interface. This catches beans that can't reliably be detected by {@code getBeanNamesForType}
 * and related operations which only work against top-level beans.
 *
 * <p>With standard Java serialization, this post-processor won't get serialized as part of
 * {@code DisposableBeanAdapter} to begin with. However, with alternative serialization
 * mechanisms, {@code DisposableBeanAdapter.writeReplace} might not get used at all, so we
 * defensively mark this post-processor's field state as {@code transient}.
 *
 * @author Juergen Hoeller
 * @since 4.3.4
 */
class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor {

	private static final Log logger = LogFactory.getLog(ApplicationListenerDetector.class);

	private final transient AbstractApplicationContext applicationContext;

	private final transient Map<String, Boolean> singletonNames = new ConcurrentHashMap<>(256);


	public ApplicationListenerDetector(AbstractApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}


	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		if (ApplicationListener.class.isAssignableFrom(beanType)) {
			this.singletonNames.put(beanName, beanDefinition.isSingleton());
		}
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (bean instanceof ApplicationListener) {
			// potentially not detected as a listener by getBeanNamesForType retrieval
			Boolean flag = this.singletonNames.get(beanName);
			if (Boolean.TRUE.equals(flag)) {
				// singleton bean (top-level or inner): register on the fly
				this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
			}
			else if (Boolean.FALSE.equals(flag)) {
				if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
					// inner bean with other scope - can't reliably process events
					logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
							"but is not reachable for event multicasting by its containing ApplicationContext " +
							"because it does not have singleton scope. Only top-level listener beans are allowed " +
							"to be of non-singleton scope.");
				}
				this.singletonNames.remove(beanName);
			}
		}
		return bean;
	}

	@Override
	public void postProcessBeforeDestruction(Object bean, String beanName) {
		if (bean instanceof ApplicationListener) {
			try {
				ApplicationEventMulticaster multicaster = this.applicationContext.getApplicationEventMulticaster();
				multicaster.removeApplicationListener((ApplicationListener<?>) bean);
				multicaster.removeApplicationListenerBean(beanName);
			}
			catch (IllegalStateException ex) {
				// ApplicationEventMulticaster not initialized yet - no need to remove a listener
			}
		}
	}

	@Override
	public boolean requiresDestruction(Object bean) {
		return (bean instanceof ApplicationListener);
	}


	@Override
	public boolean equals(@Nullable Object other) {
		return (this == other || (other instanceof ApplicationListenerDetector &&
				this.applicationContext == ((ApplicationListenerDetector) other).applicationContext));
	}

	@Override
	public int hashCode() {
		return ObjectUtils.nullSafeHashCode(this.applicationContext);
	}

}

1.postProcessMergedBeanDefinition

该bean的BeanDefination合并完了之后的,如果该bean的类是ApplicationListener子类,那么先用该bean的beanName标记该bean是不是单例,这个标记在后面bean实例化之后,判断是否要将这个ApplicationListener添加到org.springframework.context.support.AbstractApplicationContext#applicationListeners 和 org.springframework.context.support.AbstractApplicationContext#applicationEventMulticaster 中的时候用到。

这里的合并是指,当一个bean指定了parent的时候,需要把 parent 中定义的信息,合并到当前bean的BeanDefination中

2.postProcessAfterInitialization

该bean实例化之后,并且初始化之后,判断该bean是否是一个ApplicationContext类型的实例,如果不是不做处理,如果是ApplicationContext类型的实例再判断该bean是不是单例,如果是单例,就将其添加到org.springframework.context.support.AbstractApplicationContext#applicationListeners 和 org.springframework.context.support.AbstractApplicationContext#applicationEventMulticaster 以便在事件发生时能够通知到这些监听器。

之所以判断是不是单例,是因为如果一个 ApplicationListener 是非单例作用域的内部 Bean,应用上下文无法有效地管理和广播事件给这些 Bean,因为每次请求都会创建新的实例,而这些实例不在全局范围内注册。

相关推荐
10km12 分钟前
java:Apache Commons Configuration2占位符解析异常的正确解法:${prefix:name:-default}
java·apache·configuration2·变量插值·interpolation
customer0812 分钟前
【开源免费】基于SpringBoot+Vue.JS个人博客系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
灰色人生qwer20 分钟前
SpringBoot 项目配置日志输出
java·spring boot·后端
乐多_L28 分钟前
使用vue3框架vue-next-admin导出表格excel(带图片)
前端·javascript·vue.js
2301_7930698230 分钟前
Spring Boot +SQL项目优化策略,GraphQL和SQL 区别,Spring JDBC 等原理辨析(万字长文+代码)
java·数据库·spring boot·sql·jdbc·orm
阿华的代码王国36 分钟前
【从0做项目】Java搜索引擎(6)& 正则表达式鲨疯了&优化正文解析
java·后端·搜索引擎·正则表达式·java项目·从0到1做项目
服务端相声演员36 分钟前
Oracle JDK、Open JDK zulu下载地址
java·开发语言
是姜姜啊!37 分钟前
java连接redis
java·redis
hhw19911239 分钟前
spring boot知识点5
java·数据库·spring boot
EQUINOX141 分钟前
lab4 CSAPP:Cachelab
java·后端·spring