Spring原始碼 12 IOC refresh方法8
阿新 • • 發佈:2022-03-14
Spring IOC 的核心是
AbstractApplicationContext
的refresh
方法。
其中一共有 13 個主要方法,這裡分析第 8 個:initApplicationEventMulticaster
。
1 AbstractApplicationContext
1-1 初始化應用訊息廣播器
initApplicationEventMulticaster()
protected void initApplicationEventMulticaster() { // 獲取 Bean 工廠 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // 定義應用事件多播器 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); // 註冊單例 beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
獲取 Bean 工廠 和 註冊單例 在前面已經分析過,這裡不再分析。
1-2 定義應用事件多播器
SimpleApplicationEventMulticaster(beanFactory)
2 SimpleApplicationEventMulticaster
public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
// 設定 Bean 工廠
setBeanFactory(beanFactory);
}
2-1 設定 Bean 工廠
public void setBeanFactory(BeanFactory beanFactory) { if (!(beanFactory instanceof ConfigurableBeanFactory)) { throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory); } this.beanFactory = (ConfigurableBeanFactory) beanFactory; if (this.beanClassLoader == null) { this.beanClassLoader = this.beanFactory.getBeanClassLoader(); } }