一、擴展原理
1.BeanPostProcessor: bean后置處理器,bean創建對象前后進行攔截工作,比如創建bean的代理並返回
2.BeanFactoryPostProcessor: beanFactory的后置處理器,在beanFactory標准初始化之后,可以修改
beanFactory的內容,比如注冊一個bean定義
3.BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor 它定義了一個方法:
postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException,可以用來
注冊bean定義。
注:3先於2調用
二、ApplicationListener
1.設計模式:觀察者模式 發布中心:spring容器 觀察者:監聽器
應用程序可以定義觀察者,作為bean注冊到容器中:實現ApplicationListener<ApplicationEvent>接口, 實現接口中的方法(收聽功能):onApplicationEvent(ApplicationEvent arg0)
2.容器發布事件:ctx.publishEvent(new ApplicationEvent(""){})
3.如何做到每發布一個事件,監聽器就作出響應:
三、spring容器事件機制原理:
1.容器刷新事件發布到監聽器處理事件:
refresh() ——>finishRefresh()——>publishEvent(new ContextRefreshedEvent(this))——>
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType)
multicastEvent(applicationEvent, eventType)執行流程:
1. 遍歷監聽者:getApplicationListeners(event, type),然后遍歷,依次調用invokeListener(...).
invokeListener(...)——>listener.onApplicationEvent(event) 完了
2.multicastEvent多播事件就是把消息發給所有監聽者,遍歷監聽者,調用它們的收聽接口
每個監聽者都有一個接口接受發布中心推送的消息,相當於信箱。
2.容器何時注冊ApplicationEventMulticaster:
refresh()——>initApplicationEventMulticaster():
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)),就創建
bf.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,ApplicationEventMulticaster.class)
else
new SimpleApplicationEventMulticaster(beanFactory)
完。。。
3.refresh()——>registerListeners()注冊監聽者
四、@EventListener如何工作
1.finishBeanFactoryInitialization(beanFactory)——>beanFactory.preInstantiateSingletons()——>
第一次遍歷beanNames,初始化所有bean,第二次遍歷beanNames,判斷:
如果 singletonInstance instanceof SmartInitializingSingleton,就調用SmartInitializingSingleton
的方法smartSingleton.afterSingletonsInstantiated()。當遍歷到EventListenerMethodProcessor時,
就調用這個放法。
2.所以@EventListener就是利用EventListenerMethodProcessor(實現SmartInitializingSingleton接口)調用
afterSingletonsInstantiated()方法完成監聽器適配器注冊,適配器收到事件時反射調用適配的bean的收聽
方法完成事件響應。
3.afterSingletonsInstantiated()方法如何工作:還是遍歷beanNames,找到標有@EventListener注解的方法

遍歷找到的方法,EventListenerFactory.createApplicationListener(beanName, targetType, methodToUse)
如果創建出來的實例是ApplicationListenerMethodAdapter類型,添加到上下的監聽器集合中
這里用到適配器模式:ApplicationListenerMethodAdapter 實現了ApplicationListener<ApplicationEvent>
接口,這個接口提供了收聽服務,任何一個類沒有實現該接口,又想收聽事件(用自己的一個方法收聽),那么
可以把這個類關聯到適配器中,適配器負責收聽事件,然后通知它適配的類。
