簡介
ApplicationListener:監(jiān)聽容器中發(fā)布的事件。
實例
MyApplicationListener.java
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
//當(dāng)容器中發(fā)布此事件以后,方法觸發(fā)
@Override
public void onApplicationEvent(ApplicationEvent event) {
// TODO Auto-generated method stub
System.out.println("收到事件:"+event);
}
}
配置類
@ComponentScan("com.atguigu.ext")
@Configuration
public class ExtConfig {
@Bean
public Blue blue(){
return new Blue();
}
}
測試類
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
//發(fā)布事件;
applicationContext.publishEvent(new ApplicationEvent(new String("我發(fā)布的時間")) {
});
applicationContext.close();
}
原理
監(jiān)聽 ApplicationEvent 及其下面的子事件:
步驟:
1)、寫一個監(jiān)聽器(ApplicationListener實現(xiàn)類)來監(jiān)聽某個事件(ApplicationEvent及其子類)
@EventListener;
原理:使用EventListenerMethodProcessor處理器來解析方法上的@EventListener;
2)、把監(jiān)聽器加入到容器;
3)、只要容器中有相關(guān)事件的發(fā)布,我們就能監(jiān)聽到這個事件;ContextRefreshedEvent:容器刷新完成(所有bean都完全創(chuàng)建)會發(fā)布這個事件;ContextClosedEvent:關(guān)閉容器會發(fā)布這個事件;
4)、發(fā)布一個事件:applicationContext.publishEvent();
發(fā)布事件的原理:
ContextRefreshedEvent、IOCTest_Ext$1[source=我發(fā)布的時間]、ContextClosedEvent;
1)、ContextRefreshedEvent事件:a、容器創(chuàng)建對象:refresh();b、finishRefresh();容器刷新完成會發(fā)布ContextRefreshedEvent事件
2)、自己發(fā)布事件;
3)、容器關(guān)閉會發(fā)布ContextClosedEvent;
【事件發(fā)布流程】:
publishEvent(new ContextRefreshedEvent(this));
1)、獲取事件的多播器(派發(fā)器):getApplicationEventMulticaster()
2)、multicastEvent派發(fā)事件;
3)、獲取到所有的ApplicationListener;
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
a)、如果有Executor,可以支持使用Executor進行異步派發(fā);Executor executor = getTaskExecutor();
b)、否則,同步的方式直接執(zhí)行l(wèi)istener方法;invokeListener(listener, event); 拿到listener回調(diào)onApplicationEvent方法;