ApplicationListener应用与实现原理分析

LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
Survive during the day and develop at night。

目录

概述

ApplicationListener应用与实现原理分析

一、原理及源码解析

1)、ContextRefreshedEvent事件:
1)、容器创建对象:refresh();

  •  2)、finishRefresh();容器刷新完成会发布 ContextRefreshedEvent事件
    
  • 2)、自己发布事件;
  • 3)、容器关闭会发布ContextClosedEvent;

[事件发布流程】源码执行流程:
publishEvent(new ContextRefreshedEvent(this));

  •          1)、获取事件的多播器(派发器):getApplicationEventMulticaster()
    
  •          2)、multicastEvent派发事件:
    
  •          3)、获取到所有的ApplicationListener;
    

1)、如果有Executor,可以支持使用Executor进行异步派发;
Executor executor = getTaskExecutor();
2)、否则,同步的方式直接执行listener方法invokeListener(listener, event);
拿到listener回调onApplicationEvent方法;

【容器中有哪些监听器】源码执行流程:
1)、容器创建对象:refresh();
2)、registerListeners();

  •      从容器中拿到所有的监听器,把他们注册到applicationEventMulticaster中;
    
  •      String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    
  •      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    

SmartInitializingSingleton 原理:afterSingletonsInstantiated();
1)、ioc容器创建对象并refresh();
2)、finishBeanFactoryInitialization(beanFactory);初始化剩下的单实例bean
1)、先创建所有的单实例bean;getBean();
2)、获取所有创建好的单实例bean,判断是否是SmartInitializingSingleton类型的;

  •               如果是就调用afterSingletonsInstantiated()
    

ApplicationListener:监听容器中发布的事件:事件驱动模型开发
1)、写一个监听器(ApplicationListener实现类)来监听某个事件(ApplicationEvent及其子类)

  •         @EventListener;
    

原理:使用EventListenerMethodProcessor处理器来解析方法上的@EventListener;
2)、把监听器加入到容器

  •     3)、只要容器中有相关事件的发布,我们就能监听到这个事件;
    

ContextRefreshedEvent:容器刷新完成(所有bean都完全创建)会发布这个事件;
ContextClosedEvent:关闭容器会发布这个事件;

4)、发布一个事件:
applicationContext.publishEvent();

实现思路分析

相关工具如下:

分析:

小结:

参考资料和推荐阅读

1.链接: 参考资料.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值