applicationLisenter
applicationLisenter
监听容器中发布的事件。事件驱动模式开发,观察者模式
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener
监听ApplicationEvent以及下面的子事件
1、写一个监听器监(ApplicationListener实现类)听某个事件(ApplicationEvent及其子类)
@EventListener
原理:使用EventListenerMethodProcessor(实现了SmartInitializingSingleton接口),处理器来解析方法上的@EventListener
2、把监听器加入到容器;
3、只要容器中有相关事件发布,我们就能监听到这个事件:
ContextRefreshedEvent:容器刷新完成(所有bean都完成创建)会发布这个事件
ContextClosedEvent:容器关闭会发布这个事件
4、我们发布一个事件config.publishEvent
SmartInitializingSingleton原理
1)、ioc容器创建对象并refresh()
2)、finishBeanFactoryInitialization(beanFactory);初始化剩下的单实例bean
①、先创建所有的单实例bean;getBean()
②、获取所有创建好的单实例bean,是否是SmartInitializingSingleton
如果是则调用afterSingletonsInstantiated();
打一个断点到实现ApplicationListener接口的类上,看出栈入栈的方法
ContextRefreshedEvent、com.spring.ext.ExtConfig$1[source=我发布的事件]、ContextClosedEvent
1)、容器创建对象=》refresh()
2)、finishRefresh();容器刷新完成
3)、publishEvent(new ContextRefreshedEvent(this));
①事件发布流程:
1、获取事件的多播器(派发器):getApplicationEventMulticaster()
2、multicastEvent派发事件
3、获取到所有的ApplicationLisener
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
1)、如果有Executor,可以支持Executor进行异步派发
2)、否则,同步的方法执行listener
拿到listener回调onApplicationEvent(event);
事件多播器【派发器】是怎么拿到的
1)、容器创建对象:refresh()
2)、initApplicationEventMulticaster()初始化ApplicationEventMulticaster
①先去容器中找有没有applicationEventMulticaster组件
②如果没有则创建一个默认的SimpleApplicationEventMulticaster。
注册到容器中beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
容器中有哪些监听器
1)、容器创建对象:refresh()
2)、registerListeners();
从容器中拿到所有的监听器,把他们注册到getApplicationEventMulticaster
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);

浙公网安备 33010602011771号