【spring源码分析】IOC容器初始化(五)

前言:前几篇文章已经将BeanDefinition的加载过程大致分析完成,接下来继续分析其他过程。


AbstractApplicationContext#refresh

 1 public void refresh() throws BeansException, IllegalStateException {
 2         synchronized (this.startupShutdownMonitor) {
 3             // Prepare this context for refreshing.
 4             // 准备刷新上下文环境
 5             prepareRefresh();
 6 
 7             // Tell the subclass to refresh the internal bean factory.
 8             // 创建并初始化BeanFactory
 9             ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
10 
11             // Prepare the bean factory for use in this context.
12             // 填充BeanFactory
13             prepareBeanFactory(beanFactory);
14 
15             try {
16                 // Allows post-processing of the bean factory in context subclasses.
17                 // 提供子类覆盖的额外处理,即子类处理定义的BeanFactoryPostProcess
18                 postProcessBeanFactory(beanFactory);
19 
20                 // Invoke factory processors registered as beans in the context.
21                 // 激活各种BeanFactory处理器
22                 invokeBeanFactoryPostProcessors(beanFactory);
23 
24                 // Register bean processors that intercept bean creation.
25                 // 注册拦截Bean创建的Bean处理器,即注册BeanPostProcessor
26                 registerBeanPostProcessors(beanFactory);
27 
28                 // Initialize message source for this context.
29                 // 初始化上下文中的资源文件,如国际化文件的处理
30                 initMessageSource();
31 
32                 // Initialize event multicaster for this context.
33                 // 初始化上下文事件广播器
34                 initApplicationEventMulticaster();
35 
36                 // Initialize other special beans in specific context subclasses.
37                 // 给子类扩展初始化其他bean
38                 onRefresh();
39 
40                 // Check for listener beans and register them.
41                 // 在所有bean中查找listener bean,然后注册到广播器中
42                 registerListeners();
43 
44                 // Instantiate all remaining (non-lazy-init) singletons.
45                 // 初始化剩下的单例Bean(非延迟加载的)
46                 finishBeanFactoryInitialization(beanFactory);
47 
48                 // Last step: publish corresponding event.
49                 // 完成刷新过程,通知声明周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent事件通知别人
50                 finishRefresh();
51             } catch (BeansException ex) {
52                 if (logger.isWarnEnabled()) {
53                     logger.warn("Exception encountered during context initialization - " +
54                                         "cancelling refresh attempt: " + ex);
55                 }
56 
57                 // Destroy already created singletons to avoid dangling resources.
58                 // 销毁已经创建的bean
59                 destroyBeans();
60 
61                 // Reset 'active' flag.
62                 // 重置容器激活标签
63                 cancelRefresh(ex);
64 
65                 // Propagate exception to caller.
66                 throw ex;
67             } finally {
68                 // Reset common introspection caches in Spring's core, since we
69                 // might not ever need metadata for singleton beans anymore...
70                 resetCommonCaches();
71             }
72         }
73     }

再次回到refresh函数中,前面已经将preparRefresh和obtainFreshBeanFactory函数进行了分析,特别是obtainFreshBeanFactory引申出了非常多的内容,接下来我们看prepareBeanFactory函数。

AbstractApplicationContext#prepareBeanFactory

 1 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
 2         // Tell the internal bean factory to use the context's class loader etc.
 3         // 设置beanFactory的classLoader
 4         beanFactory.setBeanClassLoader(getClassLoader());
 5         // 设置beanFactory的表达式语言处理器,Spring3开始增加了对语言表达式,默认可以使用#{bean.xxx}的形式来调用相关属性值
 6         beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
 7         // 为beanFactory增加一个默认的propertyEditor
 8         beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
 9 
10         // Configure the bean factory with context callbacks.
11         // 添加ApplicationContextAwareProcessor
12         beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
13         // 设置忽略自动装配的接口
14         beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
15         beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
16         beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
17         beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
18         beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
19         beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
20 
21         // BeanFactory interface not registered as resolvable type in a plain factory.
22         // MessageSource registered (and found for autowiring) as a bean.
23         // 设置几个自动装配的特殊规则
24         beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
25         beanFactory.registerResolvableDependency(ResourceLoader.class, this);
26         beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
27         beanFactory.registerResolvableDependency(ApplicationContext.class, this);
28 
29         // Register early post-processor for detecting inner beans as ApplicationListeners.
30         beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
31 
32         // Detect a LoadTimeWeaver and prepare for weaving, if found.
33         // 增加对AspectJ的支持
34         if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
35             beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
36             // Set a temporary ClassLoader for type matching.
37             beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
38         }
39 
40         // Register default environment beans.
41         // 注册默认的系统环境bean
42         if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
43             beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
44         }
45         if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
46             beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
47         }
48         if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
49             beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
50         }
51     }

分析:

该函数的逻辑比较简单,就是对BeanFactory的一些属性进行填充,为后期实例化Bean做准备。

AbstractApplicationContext#postProcessBeanFactory该函数的默认实现为空,主要提供给子类进行自定义处理,增强扩展性。

AbstractApplicationContext#invokeBeanFactoryPostProcessors

 1     protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
 2         PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
 3 
 4         // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
 5         // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
 6         if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
 7             beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
 8             beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
 9         }
10     }

分析:

该函数的作用是激活BeanFactory的一些处理器。主要逻辑在PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

  1 public static void invokeBeanFactoryPostProcessors(
  2             ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
  3 
  4         // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  5         // 定义一个set保存所有BeanFactoryPostProcessors
  6         Set<String> processedBeans = new HashSet<>();
  7 
  8         // 如果当前BeanFactory为BeanDefinitionRegistry
  9         if (beanFactory instanceof BeanDefinitionRegistry) {
 10             BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
 11             // BeanFactoryPostProcessor集合
 12             List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
 13             // BeanDefinitionRegistryPostProcessor集合
 14             List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
 15 
 16             // 遍历beanFactoryPostProcessors
 17             for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
 18                 // 如果是BeanDefinitionRegistryPostProcessor,则调用BeanDefinitionRegistryPostProcessor进行注册
 19                 // 同时加入到registryProcessors集合中
 20                 if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
 21                     BeanDefinitionRegistryPostProcessor registryProcessor =
 22                             (BeanDefinitionRegistryPostProcessor) postProcessor;
 23                     registryProcessor.postProcessBeanDefinitionRegistry(registry);
 24                     registryProcessors.add(registryProcessor);
 25                 } else {
 26                     // 否则当做普通的BeanFactoryPostProcessor处理,添加到regularPostProcessors集合中,便于后续处理
 27                     regularPostProcessors.add(postProcessor);
 28                 }
 29             }
 30 
 31             // Do not initialize FactoryBeans here: We need to leave all regular beans
 32             // uninitialized to let the bean factory post-processors apply to them!
 33             // Separate between BeanDefinitionRegistryPostProcessors that implement
 34             // PriorityOrdered, Ordered, and the rest.
 35             // 用于保存当前处理的BeanDefinitionRegistryPostProcessor
 36             List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
 37 
 38             // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
 39             // 首先处理实现了PriorityOrdered(邮箱排序接口)的BeanDefinitionRegistryPostProcessor
 40             String[] postProcessorNames =
 41                     beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
 42             for (String ppName : postProcessorNames) {
 43                 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
 44                     currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
 45                     processedBeans.add(ppName);
 46                 }
 47             }
 48             // 排序
 49             sortPostProcessors(currentRegistryProcessors, beanFactory);
 50             // 加入registryProcessors集合
 51             registryProcessors.addAll(currentRegistryProcessors);
 52             // 调用所有实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()
 53             invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
 54             // 清空,以备下次使用
 55             currentRegistryProcessors.clear();
 56 
 57             // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
 58             // 其次,调用实现了Ordered(普通排序接口)的BeanDefinitionRegistryPostProcessor
 59             // 逻辑与上面相同
 60             postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
 61             for (String ppName : postProcessorNames) {
 62                 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
 63                     currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
 64                     processedBeans.add(ppName);
 65                 }
 66             }
 67             sortPostProcessors(currentRegistryProcessors, beanFactory);
 68             registryProcessors.addAll(currentRegistryProcessors);
 69             invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
 70             currentRegistryProcessors.clear();
 71 
 72             // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
 73             // 最后调用其他的BeanDefinitionRegistryPostProcessors
 74             boolean reiterate = true;
 75             while (reiterate) {
 76                 reiterate = false;
 77                 // 获取BeanDefinitionRegistryPostProcessors
 78                 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
 79                 for (String ppName : postProcessorNames) {
 80                     // 没有包含在processBeans中的(因为包含的都已经处理了)
 81                     if (!processedBeans.contains(ppName)) {
 82                         currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
 83                         processedBeans.add(ppName);
 84                         reiterate = true;
 85                     }
 86                 }
 87                 // 同样的逻辑
 88                 sortPostProcessors(currentRegistryProcessors, beanFactory);
 89                 registryProcessors.addAll(currentRegistryProcessors);
 90                 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
 91                 currentRegistryProcessors.clear();
 92             }
 93 
 94             // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
 95             // 调用所有BeanDefinitionRegistryPostProcessor(包括手动注册和通过配置文件注册)和BeanFactoryPostProcessor(只有手动注册)的回调函数(postProcessBeanFactory)
 96             invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
 97             invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
 98         } else {
 99             // 如果不是BeanDefinitionRegistry只需调用其回调函数(postProcessBeanFactory())即可
100             // Invoke factory processors registered with the context instance.
101             invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
102         }
103 
104         // Do not initialize FactoryBeans here: We need to leave all regular beans
105         // uninitialized to let the bean factory post-processors apply to them!
106         String[] postProcessorNames =
107                 beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
108 
109         // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
110         // Ordered, and the rest.
111         // 这里同样需要区分PriorityOrdered、Ordered和没有排序的
112         List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
113         List<String> orderedPostProcessorNames = new ArrayList<>();
114         List<String> nonOrderedPostProcessorNames = new ArrayList<>();
115         for (String ppName : postProcessorNames) {
116             // 已经处理过,则跳过
117             if (processedBeans.contains(ppName)) {
118                 // skip - already processed in first phase above
119             } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // PriorityOrdered
120                 priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
121             } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {  // Ordered
122                 orderedPostProcessorNames.add(ppName);
123             } else {// 未排序的
124                 nonOrderedPostProcessorNames.add(ppName);
125             }
126         }
127 
128         // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
129         // PriorityOrdered接口
130         sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
131         invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
132 
133         // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
134         // Ordered接口
135         List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
136         for (String postProcessorName : orderedPostProcessorNames) {
137             orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
138         }
139         sortPostProcessors(orderedPostProcessors, beanFactory);
140         invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
141 
142         // Finally, invoke all other BeanFactoryPostProcessors.
143         // 未排序的接口
144         List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
145         for (String postProcessorName : nonOrderedPostProcessorNames) {
146             nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
147         }
148         invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
149 
150         // Clear cached merged bean definitions since the post-processors might have
151         // modified the original metadata, e.g. replacing placeholders in values...
152         beanFactory.clearMetadataCache();
153     }

分析:

上述代码较长,但是处理逻辑较为单一,就是对所有的 BeanDefinitionRegistryPostProcessors 、手动注册的 BeanFactoryPostProcessor 以及通过配置文件方式的 BeanFactoryPostProcessor 按照PriorityOrdered 、 Ordered、nonOrdered 三种方式分开处理、调用。

PostProcessorRegistrationDelegate#registerBeanPostProcessors

 1 public static void registerBeanPostProcessors(
 2             ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
 3 
 4         // 获取所有的BeanPostProcessor的beanName
 5         // 这些beanName都已经全部加载到容器中去,但是没有实例化
 6         String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
 7 
 8         // Register BeanPostProcessorChecker that logs an info message when
 9         // a bean is created during BeanPostProcessor instantiation, i.e. when
10         // a bean is not eligible for getting processed by all BeanPostProcessors.
11         // 记录所有的beanProcessor数量
12         int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
13         // 注册BeanPostProcessorChecker,它主要用于在BeanPostProcessor实例化期间记录日志
14         // 当Spring中高配置的后置处理器还没有注册就已经开始了bean的实例化过程,这个时候便会打印BeanPostProcessorChecker中的内容
15         beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
16 
17         // Separate between BeanPostProcessors that implement PriorityOrdered,
18         // Ordered, and the rest.
19         // priorityOrderedPostProcessors保证顺序
20         List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
21         List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
22         // 使用Ordered保证顺序
23         List<String> orderedPostProcessorNames = new ArrayList<>();
24         // 没有顺序
25         List<String> nonOrderedPostProcessorNames = new ArrayList<>();
26         for (String ppName : postProcessorNames) {
27             // PriorityOrdered
28             if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
29                 // 调用getBean获取bean实例对象
30                 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
31                 priorityOrderedPostProcessors.add(pp);
32                 if (pp instanceof MergedBeanDefinitionPostProcessor) {
33                     internalPostProcessors.add(pp);
34                 }
35             } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
36                 // 有序
37                 orderedPostProcessorNames.add(ppName);
38             } else {
39                 // 无序
40                 nonOrderedPostProcessorNames.add(ppName);
41             }
42         }
43 
44         // First, register the BeanPostProcessors that implement PriorityOrdered.
45         // 第一步:注册所有实现了PriorityOrdered的BeanPostProcessor
46         // 排序
47         sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
48         // 注册
49         registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
50 
51         // Next, register the BeanPostProcessors that implement Ordered.
52         // 第二步:注册所有实现了Ordered的BeanPostProcessor
53         List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
54         for (String ppName : orderedPostProcessorNames) {
55             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
56             orderedPostProcessors.add(pp);
57             if (pp instanceof MergedBeanDefinitionPostProcessor) {
58                 internalPostProcessors.add(pp);
59             }
60         }
61         // 排序
62         sortPostProcessors(orderedPostProcessors, beanFactory);
63         // 注册
64         registerBeanPostProcessors(beanFactory, orderedPostProcessors);
65 
66         // Now, register all regular BeanPostProcessors.
67         // 第三步:注册所有无序的BeanPostProcessor
68         List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
69         for (String ppName : nonOrderedPostProcessorNames) {
70             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
71             nonOrderedPostProcessors.add(pp);
72             if (pp instanceof MergedBeanDefinitionPostProcessor) {
73                 internalPostProcessors.add(pp);
74             }
75         }
76         // 无序的注册,不需要排序
77         registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
78 
79         // Finally, re-register all internal BeanPostProcessors.
80         // 最后注册所有MergedBeanDefinitionPostProcessor类型的BeanPostProcessor
81         sortPostProcessors(internalPostProcessors, beanFactory);
82         registerBeanPostProcessors(beanFactory, internalPostProcessors);
83 
84         // Re-register post-processor for detecting inner beans as ApplicationListeners,
85         // moving it to the end of the processor chain (for picking up proxies etc).
86         // 加入ApplicationListenerDetector(探测器)
87         // 重新注册BeanPostProcessor以检测内部bean,因为ApplicationListenerDetector将其移动到处理器链的末尾
88         beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
89     }

分析:

上述代码虽稍微有一点长,但整体逻辑还是比较简单,就是对BeanPostProcessor进行注册,按照PriorityOrdered 、 Ordered、nonOrdered三种分支进行处理。

AbstractApplicationContext#initMessageSource

 1 protected void initMessageSource() {
 2         ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 3         // 包含"messageSource"bean
 4         if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
 5             this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
 6             // Make MessageSource aware of parent MessageSource.
 7             // 如果有父类
 8             // HierarchicalMessageSource分级处理MessageSource
 9             if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
10                 HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
11                 if (hms.getParentMessageSource() == null) {
12                     // Only set parent context as parent MessageSource if no parent MessageSource
13                     // registered already.
14                     // 如果没有注册父MessageSource,则设置为父类上下文的MessageSource
15                     hms.setParentMessageSource(getInternalParentMessageSource());
16                 }
17             }
18             if (logger.isTraceEnabled()) {
19                 logger.trace("Using MessageSource [" + this.messageSource + "]");
20             }
21         } else {
22             // 使用空MessageSource
23             // Use empty MessageSource to be able to accept getMessage calls.
24             DelegatingMessageSource dms = new DelegatingMessageSource();
25             dms.setParentMessageSource(getInternalParentMessageSource());
26             this.messageSource = dms;
27             beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
28             if (logger.isTraceEnabled()) {
29                 logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
30             }
31         }
32     }

分析:

这里主要初始化MessageSource接口实现类,主要用于国际化。

AbstractApplicationContext#initApplicationEventMulticaster

 1 protected void initApplicationEventMulticaster() {
 2         ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 3         // 如果存在applicationEventMulticaster bean,则获取赋值
 4         if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
 5             this.applicationEventMulticaster =
 6                     beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
 7             if (logger.isTraceEnabled()) {
 8                 logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
 9             }
10         } else {
11             // 如果没有,则新建SimpleApplicationEventMulticaster,并完成bean的注册
12             this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
13             beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
14             if (logger.isTraceEnabled()) {
15                 logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
16                                      "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
17             }
18         }
19     }

分析:

初始化上下文事件广播器,如果当前容器中存在 applicationEventMulticaster 的 bean,则对 applicationEventMulticaster 赋值,否则新建一个 SimpleApplicationEventMulticaster 的对象(默认的),并完成注册。

AbstractApplicationContext#onRefresh

预留给 AbstractApplicationContext 的子类用于初始化其他特殊的 bean,该方法需要在所有单例 bean 初始化之前调用。

AbstractApplicationContext#registerListeners

 1 protected void registerListeners() {
 2         // Register statically specified listeners first.
 3         // 注册静态监听器
 4         for (ApplicationListener<?> listener : getApplicationListeners()) {
 5             getApplicationEventMulticaster().addApplicationListener(listener);
 6         }
 7 
 8         // Do not initialize FactoryBeans here: We need to leave all regular beans
 9         // uninitialized to let post-processors apply to them!
10         String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
11         for (String listenerBeanName : listenerBeanNames) {
12             getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
13         }
14 
15         // Publish early application events now that we finally have a multicaster...
16         // 至此,已经完成将监听器注册到ApplicationEventMulticaster中,下面将发布前期的事件给监听器
17         Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
18         this.earlyApplicationEvents = null;
19         if (earlyEventsToProcess != null) {
20             for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
21                 getApplicationEventMulticaster().multicastEvent(earlyEvent);
22             }
23         }
24     }

分析:在所有 bean中查找 listener bean,然后注册到广播器中。

AbstractApplicationContext#finishBeanFactoryInitialization

 1 protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
 2         // Initialize conversion service for this context.
 3         // 初始化转换器
 4         if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
 5                 beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
 6             beanFactory.setConversionService(
 7                     beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
 8         }
 9 
10         // Register a default embedded value resolver if no bean post-processor
11         // (such as a PropertyPlaceholderConfigurer bean) registered any before:
12         // at this point, primarily for resolution in annotation attribute values.
13         // 如果之前没有注册bean后置处理器,则注册默认的解析器
14         if (!beanFactory.hasEmbeddedValueResolver()) {
15             beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
16         }
17 
18         // 初始化 Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
19         String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
20         for (String weaverAwareName : weaverAwareNames) {
21             getBean(weaverAwareName);
22         }
23 
24         // Stop using the temporary ClassLoader for type matching.
25         // 停止使用临时的classLoader
26         beanFactory.setTempClassLoader(null);
27 
28         // Allow for caching all bean definition metadata, not expecting further changes.
29         beanFactory.freezeConfiguration();
30 
31         // Instantiate all remaining (non-lazy-init) singletons.
32         // 初始化所有剩余的单例(非延迟初始化)
33         beanFactory.preInstantiateSingletons();
34     }

分析:初始化剩下的单例Bean(非延迟加载的)

AbstractApplicationContext#finishRefresh

 1 protected void finishRefresh() {
 2         // Clear context-level resource caches (such as ASM metadata from scanning).
 3         clearResourceCaches();
 4 
 5         // Initialize lifecycle processor for this context.
 6         initLifecycleProcessor();
 7 
 8         // Propagate refresh to lifecycle processor first.
 9         getLifecycleProcessor().onRefresh();
10 
11         // Publish the final event.
12         publishEvent(new ContextRefreshedEvent(this));
13 
14         // Participate in LiveBeansView MBean, if active.
15         LiveBeansView.registerApplicationContext(this);
16     }

分析:完成刷新过程,通知生命周期处理器 lifecycleProcessor 刷新过程,同时发出 ContextRefreshEvent 通知别人

总结

本文只是对AbstractApplicationContext的一些方法进行了简要介绍,并没有进行非常详细的分析,因为加载BeanDefinition阶段才是我们的重点,现在BeanDefinition有了,接下来就是看spring是如何实例化Bean了。


by Shawn Chen,2018.12.25日,晚。

posted @ 2018-12-25 19:48  developer_chan  阅读(543)  评论(0编辑  收藏  举报