目录
一、概述
二、invokeBeanFactoryPostProcessors(beanFactory):执行BeanFactoryPostProcessor后置处理器的postProcessBeanFactory()增强方法
三、registerBeanPostProcessors(beanFactory):注册BeanPostProcessor
四、initMessageSource():为上下文初始化MessageSource
五、initApplicationEventMulticaster():初始化事件多播器
六、onRefresh():模板方法,留给子类初始化其他的bean
七、registerListeners():注册监听器
一、概述
前面一篇文章我们详细分析了Spring IOC容器启动方法refresh()方法的前面四个方法,简单回顾一下:
- prepareRefresh():创建 Bean 容器前的准备工作;
- obtainFreshBeanFactory():创建Bean容器,解析XML配置,封装成bean定义信息;
- prepareBeanFactory(beanFactory):准备Bean工厂,设置一些属性;
- postProcessBeanFactory(beanFactory):留给子类对BeanFactory定制化处理;
如果没有阅读前面一篇文章的读者,可以先阅读前面一篇文章Spring IOC源码笔记(一)_weixiaohuai的博客-CSDN博客,连贯起来有助于理解。
本篇文章我们接着分析refresh()方法的其他几个方法:
- invokeBeanFactoryPostProcessors(beanFactory):执行BeanFactoryPostProcessor后置处理器的postProcessBeanFactory()增强方法;
-
registerBeanPostProcessors(beanFactory):注册BeanPostProcessor;
-
initMessageSource():为上下文初始化MessageSource;
-
initApplicationEventMulticaster():初始化事件多播器;
-
onRefresh():模板方法,留给子类初始化其他的bean;
-
registerListeners():注册监听器;
二、invokeBeanFactoryPostProcessors(beanFactory):执行BeanFactoryPostProcessor后置处理器的postProcessBeanFactory()增强方法其中标红的几个方法是IOC中的重要方法,读者可以多留意具体实现。
invokeBeanFactoryPostProcessors(beanFactory)方法会实例化和调用所有 BeanFactoryPostProcessor(包括其子类 BeanDefinitionRegistryPostProcessor)。
首先需要明白BeanFactoryPostProcessor是什么?
BeanFactoryPostProcessor,Bean工厂增强器,是 Spring 初始化 BeanFactory 时对外暴露的扩展点,Spring IoC 容器允许 BeanFactoryPostProcessor 在容器实例化任何 bean 之前读取 bean 的定义,并可以修改它。
其定义如下:
@FunctionalInterface public interface BeanFactoryPostProcessor { void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException; }
BeanFactoryPostProcessor是一个函数式接口,内部包含一个postProcessBeanFactory()方法,当我们自定义BeanFactoryPostProcessor后,在invokeBeanFactoryPostProcessors()方法中就会回调我们自定义的那些BeanFactoryPostProcessor的postProcessBeanFactory()方法:
// 实例化并调用所有已注册的BeanFactoryPostProcessor. protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { // 1.拿到当前应用上下文beanFactoryPostProcessors变量中的值 // 2.实例化并调用所有已注册的BeanFactoryPostProcessor PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
关键逻辑在invokeBeanFactoryPostProcessors()方法中,代码如下:
public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, ListbeanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. // 记录已经处理过的BeanFactoryPostProcessor集合,无需重复执行 Set processedBeans = new HashSet<>(); // 对BeanDefinitionRegistry类型的处理 if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; // 存放普通的BeanFactoryPostProcessor List regularPostProcessors = new ArrayList<>(); // 存放BeanDefinitionRegistryPostProcessor,BeanDefinitionRegistryPostProcessor继承了BeanFactoryPostProcessor List registryProcessors = new ArrayList<>(); // 循环遍历硬编码方式注册的BeanFactoryPostProcessor后置处理器 for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { // 区分普通的BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor,分别放入不同的集合中 if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; // 如果是BeanDefinitionRegistryPostProcessor的话,直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法 registryProcessor.postProcessBeanDefinitionRegistry(registry); // BeanDefinitionRegistryPostProcessor registryProcessors.add(registryProcessor); } else { // 普通BeanFactoryPostProcessor regularPostProcessors.add(postProcessor); } } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. // 记录本次要执行的BeanDefinitionRegistryPostProcessor List currentRegistryProcessors = new ArrayList<>(); // 配置注册的后置处理器 // 1、调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类 // 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); // 循环遍历,判断是否实现PriorityOrdered接口 for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); // 添加到将要执行的集合中,避免重复执行 processedBeans.add(ppName); } } // 按照优先级进行排序 sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); // 调用BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // 2、调用所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor实现类 // 找出所有实现BeanDefinitionRegistryPostProcessor接口的类 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); // 循环遍历,判断是否实现Ordered接口 for (String ppName : postProcessorNames) { // 未执行过 && 实现Ordered接口 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); // 添加到将要执行的集合中,避免重复执行 processedBeans.add(ppName); } } // 按照order排序 sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); // 调用BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // 3、调用所有剩下的BeanDefinitionRegistryPostProcessors boolean reiterate = true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 未执行过的 if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } // 排序 sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); // 调用BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); } // 回调所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); // 回调普通BeanFactoryPostProcessor的postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // 调用在上下文实例中注册的工厂处理器 invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 从bean工厂中获取到BeanFactoryPostProcessor String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 存放实现了PriorityOrdered接口的BeanFactoryPostProcessor List priorityOrderedPostProcessors = new ArrayList<>(); // 存放实现了Ordered接口的BeanFactoryPostProcessor List orderedPostProcessorNames = new ArrayList<>(); // 存放其它BeanFactoryPostProcessor List nonOrderedPostProcessorNames = new ArrayList<>(); // 循环从工厂中获取的BeanFactoryPostProcessor, 分别存入到三个不同的集合中 for (String ppName : postProcessorNames) { // 针对已经处理过的BeanFactoryPostProcessor,不做任何 *** 作,无需重复执行 if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // PriorityOrdered接口的BeanFactoryPostProcessor priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { // Ordered接口的BeanFactoryPostProcessor orderedPostProcessorNames.add(ppName); } else { // 普通BeanFactoryPostProcessor nonOrderedPostProcessorNames.add(ppName); } } // 1、调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor // 排序 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 执行postProcessBeanFactory()回调 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // 2、调用所有实现Ordered接口的BeanFactoryPostProcessor List orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } // 排序 sortPostProcessors(orderedPostProcessors, beanFactory); // 执行postProcessBeanFactory()回调 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // 3、调用所有其他BeanFactoryPostProcessor List nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } // 执行postProcessBeanFactory()回调 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... // 清除元数据缓存 beanFactory.clearmetadataCache(); }
执行完invokeBeanFactoryPostProcessors(beanFactory)方法,观察控制台输出:
===========================实例化之前=========================== 执行MyBeanFactoryPostProcessor的postProcessBeanFactory()方法
简单总结一下invokeBeanFactoryPostProcessors(beanFactory)方法:
- a、处理实现了BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor,并按照实现了PriorityOrdered 接口、Ordered 接口、普通BeanFactoryPostProcessor顺序,依次回调postProcessBeanDefinitionRegistry()和postProcessBeanFactory()方法;
- b、处理实现了BeanFactoryPostProcessor接口的bean,同样按照按照实现了PriorityOrdered 接口、Ordered 接口、普通BeanFactoryPostProcessor顺序,依次回调postProcessBeanFactory()方法;
- c、最后,清除元数据缓存;
registerBeanPostProcessors(beanFactory)主要是将所有实现了BeanPostProcessor接口的类注册到BeanFactory 中。注意,只是完成了注册工作,并没有执行BeanPostProcessor的增强逻辑,真正执行是在bean初始化前、后,后面我们看到bean初始化逻辑的时候可以看到。
首先需要明白什么BeanPostProcessor是什么?
BeanPostProcessor是bean的后置处理器,它允许我们在bean实例化后,在bean初始化前、初始化后,对bean实例进行修改。BeanPostProcessor是一个接口,其定义如下:
public interface BeanPostProcessor { // bean初始化前执行 @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } // bean初始化后执行 @Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
在bean实例化之后,执行初始化方法前会调用所有BeanPostProcessor的 postProcessBeforeInitialization()方法,在执行初始化方法后会调用所有 BeanPostProcessor 的 postProcessAfterInitialization()方法。
读者需要注意区分BeanFactoryPostProcessor 和 BeanPostProcessor。
- BeanFactoryPostProcessor 是针对 BeanFactory 的扩展,主要用在 bean 实例化之前,读取 bean 的定义,允许我们修改它;
- BeanPostProcessor 是针对 bean 的扩展,主要用在 bean 实例化之后,执行初始化方法前后,允许我们对 bean 实例进行修改;
接下来,我们看下registerBeanPostProcessors(beanFactory)方法的核心逻辑:
// 注册BeanPostProcessor,注意,这里还不会执行BeanPostProcessor对应的增强方法 // 真正调用是在bean初始化前、初始化后 protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }
核心逻辑在registerBeanPostProcessors()方法,源码如下:
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { // 1、从bean工厂中获取到所有实现了BeanPostProcessor接口的bean // 如本例中我们自定义的MyBeanPostProcessor就会在这里被扫描出 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; // 往bean工厂中添加一个BeanPostProcessor -> BeanPostProcessorChecker // BeanPostProcessorChecker是一个在创建bean期间记录信息消息的BeanPostProcessor beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // 存放实现了PriorityOrdered接口的BeanPostProcessor ListpriorityOrderedPostProcessors = new ArrayList<>(); // 存放实现了MergedBeanDefinitionPostProcessor接口的BeanPostProcessor List internalPostProcessors = new ArrayList<>(); // 存放实现了Ordered接口的BeanPostProcessor List orderedPostProcessorNames = new ArrayList<>(); // 存放普通的BeanPostProcessor List nonOrderedPostProcessorNames = new ArrayList<>(); // 2、循环遍历扫描出的所有的BeanPostProcessor,然后分别存放到前面定义的几个集合中 for (String ppName : postProcessorNames) { // 实现了PriorityOrdered接口的BeanPostProcessor if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 通过getBean获取对应的Bean实例,然后添加到priorityOrderedPostProcessors集合中 // 这里涉及到获取bean的过程,暂且不深入分析 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); // 如果同时实现了MergedBeanDefinitionPostProcessor接口,加入到internalPostProcessors集合中 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { // 实现了Ordered接口的BeanPostProcessor orderedPostProcessorNames.add(ppName); } else { // 普通BeanPostProcessor nonOrderedPostProcessorNames.add(ppName); } } // 排序 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 3、注册实现了PriorityOrdered接口的BeanPostProcessor registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); List orderedPostProcessors = new ArrayList<>(); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); // 如果同时实现了MergedBeanDefinitionPostProcessor接口,加入到internalPostProcessors集合中 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } // 排序 sortPostProcessors(orderedPostProcessors, beanFactory); // 4、注册实现了Ordered接口的BeanPostProcessor // 通过beanFactory.addBeanPostProcessor(postProcessor)添加BeanPostProcessor registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. // 5、注册其他普通的BeanPostProcessor List nonOrderedPostProcessors = new ArrayList<>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); // 如果同时实现了MergedBeanDefinitionPostProcessor接口,加入到internalPostProcessors集合中 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } // 通过beanFactory.addBeanPostProcessor(postProcessor)添加BeanPostProcessor registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // 排序 sortPostProcessors(internalPostProcessors, beanFactory); // 通过beanFactory.addBeanPostProcessor(postProcessor)添加BeanPostProcessor // 6、注册所有内部 BeanPostProcessor registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 7、往bean工厂中添加一个BeanPostProcessor -> ApplicationListenerDetector // ApplicationListenerDetector beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
可以看到,处理逻辑跟之前BeanFactoryPostProcessor类似,同样按照实现了PriorityOrdered 接口、Ordered 接口、普通BeanPostProcessor的顺序,然后注册到bean工厂中。注册给定的BeanPostProcessor主要是在registerBeanPostProcessors()方法中实现的:
// 注册给定的BeanPostProcessor private static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, ListpostProcessors) { // 遍历给定的BeanPostProcessor集合,挨个通过addBeanPostProcessor方法,向bean工厂中添加,保存到BeanFactory的beanPostProcessors成员变量中 // private final List beanPostProcessors = new CopyOnWriteArrayList<>(); for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); } }
我们可以看到,通过遍历前面扫描出来的BeanPostProcessor集合,然后调用addBeanPostProcessor方法,向bean工厂中添加指定的BeanPostProcessor:
//org.springframework.beans.factory.support.AbstractBeanFactory#addBeanPostProcessor public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null"); // 如果当前beanPostProcessor已经存在,则先移除 this.beanPostProcessors.remove(beanPostProcessor); // Track whether it is instantiation/destruction aware if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } // 将beanPostProcessor添加到beanPostProcessors成员属性中 // private final ListbeanPostProcessors = new CopyOnWriteArrayList<>(); this.beanPostProcessors.add(beanPostProcessor); }
并且注册后的BeanPostProcessor保存在BeanFactory的成员变量beanPostProcessors中:
// 存放工厂中所有的BeanPostProcessor实例 private final ListbeanPostProcessors = new CopyOnWriteArrayList<>();
到这里,BeanPostProcessor已经成功注册到bean工厂中了,但是我们看到,这里并没有执行BeanPostProcessor的增强方法,实际上BeanPostProcessor的增强是在bean初始化前、初始化后阶段执行。
简单总结一下registerBeanPostProcessors(beanFactory)方法:
- a、从bean工厂中获取到所有实现了BeanPostProcessor接口的bean;
- b、循环遍历扫描出的所有的BeanPostProcessor,然后分别存放到几个集合中;
- c、注册实现了PriorityOrdered接口的BeanPostProcessor;
- d、注册实现了Ordered接口的BeanPostProcessor;
- e、注册其他普通的BeanPostProcessor;
- f、注册所有内部 BeanPostProcessor;
- g、往bean工厂中添加一些BeanPostProcessor ,如BeanPostProcessorChecker、ApplicationListenerDetector;
initMessageSource()主要是完成MessageSource消息源的初始化,用于国际化处理。总体实现思路也比较清晰:
- 获取到bean工厂;
- 判断工厂中是否包含id为messageSource的bean,即用户自定义的消息源;
- 如果存在用户自定义的MessageSource,则使用用户自定义的;否则新建一个默认的消息源,并注册到bean工厂中;
源码如下:
// 为上下文初始化MessageSource,即不同语言的消息体,即国际化处理 protected void initMessageSource() { // 1、获取到当前的bean工厂对象,类型为DefaultListableBeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 2、判断bean工厂中是否存在id为messageSource的bean if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { // 3、如果存在,从bean工厂中获取到对应的bean,判断获取的bean是不是HierarchicalMessageSource类型的,如果是的话,则设置其父级消息源 this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // only set parent context as parent MessageSource if no parent MessageSource registered already. // 如果尚未注册父消息源,则将父上下文设置为父消息源 hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // 4、如果bean工厂中不存在名称为messageSource的bean对象,则新建DelegatingMessageSource类作为messageSource的Bean,并注册到bean工厂中 // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); // 设置父消息源 dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; // 把.messageSource作为单例Bean注册到bean工厂中,存入一级缓存singletonObjects中 beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }五、initApplicationEventMulticaster():初始化事件多播器
initApplicationEventMulticaster()用于初始化事件多播器,方法实现比较简单:先判断有没有用户自定义的ApplicationEventMulticaster事件多播器,没有的话就新建一个SimpleApplicationEventMulticaster,并作为单例bean注册到bean工厂。
源码如下:
// 初始化事件多播器 protected void initApplicationEventMulticaster() { // 获取到当前bean工厂 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 1、如果用户自定义了事件广播器,那么使用用户自定义的事件广播器(实现ApplicationEventMulticaster接口) // 判断bean工厂中是否存在id为applicationEventMulticaster的bean if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { // 如果存在,则通过getBean获取对应的bean this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // 2、如果用户没有自定义事件广播器,则使用默认的事件广播器:SimpleApplicationEventMulticaster // 如果不存在,则新建一个简单的SimpleApplicationEventMulticaster事件多播器 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); // 作为单例bean注册到bean工厂,存入一级缓存singletonObjects中 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() + "]"); } } }六、onRefresh():模板方法,留给子类初始化其他的bean
onRefresh()又是一个Spring留给我们进行扩展的点,典型的模板方法,项目中如果有需要初始化其他的bean的场景,可以通过重写onRefresh()方法来实现。
// 模板方法,留给子类初始化其他的bean protected void onRefresh() throws BeansException { // For subclasses: do nothing by default. }七、registerListeners():注册监听器
registerListeners()完成监听器的注册工作,整体思路:
- 获取通过硬编码调用addApplicationListener方法添加的监听器,注册到前面初始化好的事件多播器中;
- 从bean工厂中找出所有实现了ApplicationListener接口的bean名称,循环添加到事件多播器中;
- 如果存在早期应用事件, 则直接发布早期的应用程序事件到相应的监听器,并将earlyApplicationEvents早期事件置为空;
Spring监听器使用到了典型的设计模式 - 观察者模式,源码如下:
// 注册监听器 protected void registerListeners() { // 1. 获取静态指定的监听器集合,循环添加到事件多播器中,事件多播器在前面一个步骤initApplicationEventMulticaster()中已经初始化 // getApplicationListeners()就是获取的AbstractApplicationContext#applicationListeners成员属性的值,即通过硬编码调用addApplicationListener方法添加的监听器 for (ApplicationListener> listener : getApplicationListeners()) { // 把手动注册的监听器添加到事件多播器中,这里直接添加的是类型是ApplicationListener getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 2. 从bean工厂中找出所有实现了ApplicationListener接口的bean名称,循环添加到事件多播器中 // 通过配置文件或注解注入的监听器 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { // 由于实现了ApplicationListener接口的类此时还没有实例化,这里添加的是监听器对应的bean的名称,在获取所有的事件监听器方法AbstractApplicationEventMulticaster.DefaultListenerRetriever#getApplicationListeners中,会通过beanFactory.getBean(listenerBeanName, ApplicationListener.class)获取到对应的监听器bean getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // 3. 如果存在早期应用事件, 则直接发布早期的应用程序事件到相应的监听器,并将earlyApplicationEvents早期事件置为空 //早期应用程序事件this.earlyApplicationEvents在AbstractApplicationContext#prepareRefresh()方法中已经初始化 Set earlyEventsToProcess = this.earlyApplicationEvents; // 清空早期应用程序事件 this.earlyApplicationEvents = null; // 如果早期应用程序事件不为空,则直接执行multicastEvent()方法发布事件 if (!CollectionUtils.isEmpty(earlyEventsToProcess)) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
好了,本篇文章暂且先分析前面几个方法的具体实现,到这里,refresh方法还剩下最后两个没有分析,咱们放到下篇文章来单独分析,如下:
- finishBeanFactoryInitialization(beanFactory):初始化所有剩下的非懒加载的单例Bean;
- finishRefresh():完成上下文的刷新工作;
希望本篇文章对读者有所帮助,也希望大家能反馈表述错误或不合理的地方。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)