• spring5.0 源码解析(day07) registerListeners();


    spring5.0 源码解析(day07) registerListeners


    接着上一篇文章的坑 initApplicationEventMulticaster() 这篇文章先来看一下 registerListeners 是如何实现的

    registerListeners

    registerListeners() 这人个方法作用:检查监听器的bean 之后向容器中注册

    // 首先注册静态指定的侦听器。   手动放入的 listener
    		for (ApplicationListener<?> listener : getApplicationListeners()) {
    			// 将监听器 放入多播事件中
    			getApplicationEventMulticaster().addApplicationListener(listener);
    		}
    
    		//  从容器中获取所有实现了ApplicationListener接口的bd的bdName
    		//  放入applicationListenerBeans
    		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    		for (String listenerBeanName : listenerBeanNames) {
    			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    		}
    
    		// 这里先发布早期的监听器. (earlyEventsToProcess )在广播设置之前发布的ApplicationEvent
    		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    		this.earlyApplicationEvents = null;
    		// 执行
    		if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
    			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
    				getApplicationEventMulticaster().multicastEvent(earlyEvent);
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    earlyEventsToProcess

    这里有一个不好理解的点 earlyEventsToProcess
    earlyApplicationEvents用来存放容器启动后需要发布的事件。它会在容器启动的prepareRefresh环节初始化为一个LinkedHashSet。(如果对spring的初始化流程不熟悉,请参考附录中的内容)

    他是在 prepareRefresh 环节被创建 , 在 registerListeners 结束后被调用 并且会被清空 , 也就是我我们可以在容器初始化过程中 添加想要在 registerListeners 执行之后 监听器 , 并且只执行一次, 那他到底有什么左右呢 ? 查了很多资料也没有找到,我想的是 如果需要我们自定义实现容易时 那么也就可以在这里添加事件去执行了 害!! 有懂得大佬欢迎指教

    if (this.earlyApplicationListeners == null) {
    			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    		}
    		else {
    			// 将本地应用程序侦听器重置为预刷新状态.
    			this.applicationListeners.clear();
    			this.applicationListeners.addAll(this.earlyApplicationListeners);
    		}
    
    		// Allow for the collection of early ApplicationEvents,
    		// to be published once the multicaster is available...
    		// 创建多播list
    		this.earlyApplicationEvents = new LinkedHashSet<>();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    我赢助手之爆款内容创作:爆款内容的四大特性,梳理下自己的账号吧?
    Python实用技术二:数据分析和可视化(2)
    企业级软件开发流程
    ECMAScript6(ES6)基础语法
    《QT从基础到进阶·十五》用鼠标绘制矩形(QGraphicsView、QPainter、QGraphicsRectItem)
    HJ33整数与IP地址间的转换
    微信小程序 限制字数文本域框组件封装
    3BHE022291R0101 PCD230A 专注于制造卓越人工智能
    【Debian 9(Stretch)】linux系统下安装gcc-9.3.0
    C语言进阶指针(3) ——qsort的实现
  • 原文地址:https://blog.csdn.net/qq_44808472/article/details/126194199