Spring中ApplicationListener实现监听原理

2024-04-02 15:28

本文主要是介绍Spring中ApplicationListener实现监听原理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • ApplicationListener使用方式
  • ApplicationListener实现原理
    • 1.引入并实例化时机
    • 2.作用时机
    • 3.发布事件,生效
  • 总结

ApplicationListener使用方式

package com.cyl.listener;import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;@Component
public class CylOrderFistListener implements ApplicationListener {@Overridepublic void onApplicationEvent(ApplicationEvent event) {System.out.println(event);}
}

ApplicationListener实现原理

ApplicationListener主要是通过ApplicationListenerDetector类实现的,是一个bean的后置处理器,主要识别出所有实现了ApplicationListener的对象,然后注册到spring容器的监听器属性中
在这里插入图片描述
后续将通过new AnnotationConfigApplicationContext为入口调试代码去讲解ApplicationListenerDetector的作用机制。

package com.cyl;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {// 创建一个Spring容器AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();context.register(AppConfig.class);context.refresh();}
}

1.引入并实例化时机

当执行容器的refresh方法时,会执行registerBeanPostProcessors方法,该方法会将将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去在这里插入图片描述
最终会调用到org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext),最后一步会将ApplicationListenerDetector实例化,添加bean工厂的后置处理器列表内。
在这里插入图片描述

2.作用时机

在实例化bean的后置处理器后,容器接下来会实例化所有非懒加载的bean对象,即执行org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization,在实例化所有懒加载所有对象时,ApplicationListenerDetector作为bean的后置处理器会处理所有的非懒加载的bean对象,判断该对象是否实现了ApplicationListener,若是则注册到容器的监听器列表中
在这里插入图片描述ApplicationListenerDetector实现了MergedBeanDefinitionPostProcessor接口,重写了
postProcessMergedBeanDefinition和postProcessAfterInitialization,两个方法分别在bean的实例化后初始化后执行
在这里插入图片描述

postProcessMergedBeanDefinition该方法是在bean生命周期的实例化后执行,该方法的逻辑判断目前的bean是否实现了ApplicationListener接口,若是则记录到ApplicationListenerDetector对象的singletonNames属性中


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

postProcessAfterInitialization该方法是在bean生命周期的初始化后执行,主要是bean初始化后判断属性singletonNames是否有当前beanName,若有则注册到容器的监听器列表内

@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {if (bean instanceof ApplicationListener) {// potentially not detected as a listener by getBeanNamesForType retrievalBoolean flag = this.singletonNames.get(beanName);if (Boolean.TRUE.equals(flag)) {// singleton bean (top-level or inner): register on the flythis.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 eventslogger.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;}

3.发布事件,生效

容器初始化最后阶段,即执行org.springframework.context.support.AbstractApplicationContext#finishRefresh
在这里插入图片描述
会发布事件并通知所有容器内的监听器在这里插入图片描述最终效果图为:在这里插入图片描述

总结

ApplicationListener实现监听的原理就是使用了ApplicationListenerDetector类,这是一个bean后置处理器,在容器启动中,ApplicationListenerDetector先被实例化,然后实例化其他非懒加载的bean对象时,ApplicationListenerDetector会作用于这些非懒加载的bean对象,判断对象是否实现了ApplicationListener接口,若实现了则注册到容器的监听器列表中。待容器内发布相关事件时,获取到所有监听该事件的监听器,执行对应的监听方法

这篇关于Spring中ApplicationListener实现监听原理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/870346

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter