ApplicationListener
ApplicationListener監聽容器中發佈的事件,用於事件驅動模型開發;實現ApplicationListener<E extends ApplicationEvent>接口監聽 ApplicationEvent 及其下面的子事件。首先添加監聽器實現
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
//當容器中發佈此事件以後,方法觸發
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("收到事件:" + event);
}
}
使用IOCTest_Ext.java進行測試
這兩個事件也都是ApplicationEvent下的事件
自定義事件
步驟
1)寫一個監聽器(ApplicationListener實現類)來監聽某個事件(ApplicationEvent及其子類)
2)把監聽器加入到容器;
3)只要容器中有相關事件的發佈,我們就能監聽到這個事件;
ContextRefreshedEvent:容器刷新完成(所有bean都完全創建)會發布這個事件;
ContextClosedEvent:關閉容器會發布這個事件;
4)發佈一個事件:applicationContext.publishEvent();
在容器中發佈事件
@Test
public void test01() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
//發佈事件;
applicationContext.publishEvent(new ApplicationEvent("我發佈的事件") {
});
applicationContext.close();
}
運行結果
原理
上面例子中一共存在3個事件ContextRefreshedEvent、IOCTest_Ext$1[source=我發佈的時間]、ContextClosedEvent。
1)、ContextRefreshedEvent事件:
1)、容器創建對象:refresh();
2)、finishRefresh();容器刷新完成會發布ContextRefreshedEvent事件
2)、自己發佈事件;
3)、容器關閉會發布ContextClosedEvent;
【事件發佈流程】:
3)、publishEvent(new ContextRefreshedEvent(this));
1)、獲取事件的多播器(派發器):getApplicationEventMulticaster()
2)、multicastEvent派發事件:
3)、獲取到所有的ApplicationListener;
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
1)、如果有Executor,可以支持使用Executor進行異步派發;
Executor executor = getTaskExecutor();
2)、否則,同步的方式直接執行listener方法;invokeListener(listener, event);
拿到listener回調onApplicationEvent方法;
【事件多播器(派發器)】
1)、容器創建對象:refresh();
2)、initApplicationEventMulticaster();初始化ApplicationEventMulticaster;
1)、先去容器中找有沒有id=“applicationEventMulticaster”的組件;
2)、如果沒有this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
並且加入到容器中,我們就可以在其他組件要派發事件,自動注入這個applicationEventMulticaster;
【容器中有哪些監聽器】
1)、容器創建對象:refresh();
2)、registerListeners();
從容器中拿到所有的監聽器,把他們註冊到applicationEventMulticaster中;
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
//將listener註冊到ApplicationEventMulticaster中
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
我們可以自定義事件派發器ApplicationEventMulticaster和執行器Executor進行異步派發
@EventListener
原理:使用EventListenerMethodProcessor處理器來解析方法上的@EventListener;
SmartInitializingSingleton 原理:->afterSingletonsInstantiated();
1)、ioc容器創建對象並refresh();
2)、finishBeanFactoryInitialization(beanFactory);初始化剩下的單實例bean;
1)、先創建所有的單實例bean;getBean();
2)、獲取所有創建好的單實例bean,判斷是否是SmartInitializingSingleton類型的;如果是就調用afterSingletonsInstantiated();