接下来看初始化事件传播器和将所有ApplicationListener注册到时间传播器中这两块内容
初始化事件传播器
- 如果容器中已经有名称为applicationEventMulticaster的单实例bean或者BeanDefinition,则通过beanFactory.getBean()获取bean对象,并赋值给成员变量applicationEventMulticaster
- 如果容器中没有,则创建一个SimpleApplicationEventMulticaster类型的对象赋值给成员变量applicationEventMulticaster,并注册到容器中
protected void initApplicationEventMulticaster() {
//获取bean工厂
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
//如果容器中已经有名称为applicationEventMulticaster的单实例bean或者BeanDefinition
//则通过beanFactory.getBean()获取bean对象,并赋值给成员变量applicationEventMulticaster
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
} else {
//如果容器中没有,则创建一个SimpleApplicationEventMulticaster类型的对象赋值给成员变量applicationEventMulticaster
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
//将applicationEventMulticaster 注册到bean工厂中
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() + "]");
}
}
}
将所有ApplicationListener注册到时间传播器中
- 从容器中拿到所有的ApplicationListener
- 将每个监听器添加到事件派发器中;getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
- 派发之前步骤产生的事件;
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 获取到所有的ApplicationListener的bean名称
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
//添加到事件传播期中
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
//派发之前产生的事件
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}