Spring IOC——源码分析
阅读原文时间:2023年07月09日阅读:6

1 //下面每一个方法都会单独提出来进行分析
2 @Override
3 public void refresh() throws BeansException, IllegalStateException {
4 synchronized (this.startupShutdownMonitor) {
5 // 刷新前的预处理
6 prepareRefresh();
7 // 获取 Bean工厂,默认的 DefaultListableBeanFactory
8 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
9 // 准备bean工厂以供在此上下文中使用(对刚创建的bean工厂进行设置)
10 prepareBeanFactory(beanFactory);
11 try {
12 // 允许在子类中对bean工厂进行后处理。目前是一个空实现
13 //beanFactory 准备工作完成后进行的后置处理工作。
14 postProcessBeanFactory(beanFactory);
15 // 调用 BeanFactoryPostProcessors,
16 //BeanFactoryPostProcessor:在 beanFactory 标准初始化完成之后执行的
17 //两个接口 BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
18 invokeBeanFactoryPostProcessors(beanFactory);
19 // 注册bean的处理器,拦截bean的创建过程
20 registerBeanPostProcessors(beanFactory);
21 // 初始化messagesource 组件,做国际化功能、消息绑定、消息解析.
22 initMessageSource();
23 // 初始化事件派发器
24 initApplicationEventMulticaster();
25 // 初始化特定子类中的其他特殊bean。留给子容器(子类)是一个空的实现
26 // 子类重写这个方法,在容器刷新的时候可以自定义逻辑
27 onRefresh();
28 // 将容器中将所有项目里面的 applicationLister 注册进来
29 registerListeners();
30 // 初始化所有剩下的单实例bean singletons.
31 finishBeanFactoryInitialization(beanFactory);
32 // 最后一步:刷新Bean工厂容器。
33 finishRefresh();
34 }

【1】prepareRefresh 刷新前的预处理源码分析:

1 protected void prepareRefresh() {
2 // 记录当前时间和容器的状态
3 this.startupDate = System.currentTimeMillis();
4 this.closed.set(false);
5 this.active.set(true);
6 // 在上下文环境中初始化属性设置,其底层是个空方法,由具体的子类定义其实现。
7 initPropertySources();
8 // 验证属性的合法性
9 getEnvironment().validateRequiredProperties();
10 //保存一些早期的容器事件
11 this.earlyApplicationEvents = new LinkedHashSet();
12 }

【2】obtainFreshBeanFactory 获取 Bean工厂源码分析

1 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
2 //创建 beanFactory
3 refreshBeanFactory();
4 //获取 beanFactory
5 return getBeanFactory();
6 }
7
8 //refreshBeanFactory 源码展示,位于GenericApplicationContext类
9 //创建 GenericApplicationContext 类的时候,默认会创建一个 bean 工厂。
10 public GenericApplicationContext() {
11 this.beanFactory = new DefaultListableBeanFactory();
12 }
13 @Override
14 protected final void refreshBeanFactory() throws IllegalStateException {
15 if (!this.refreshed.compareAndSet(false, true)) {
16 throw new IllegalStateException(
17 "GenericApplicationContext … once");
18 }
19 //*** 给 bean工厂中创建一个序列化ID
20 this.beanFactory.setSerializationId(getId());
21 }
22
23 //获取一个 bean 工厂
24 @Override
25 public final ConfigurableListableBeanFactory getBeanFactory() {
26 return this.beanFactory;
27 }

【3】prepareBeanFactory 对刚创建的bean工厂进行设置,源码分析:

1 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
2 // 告诉内部bean工厂使用上下文的类加载器等。
3 beanFactory.setBeanClassLoader(getClassLoader());
4 //设置表达式解析器等
5 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
6 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
7
8 // 添加部分后置处理器 ApplicationContextAwareProcessor
9 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
10 //设置忽略的自动装配的接口
11 beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
12 beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
13 beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
14 beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
15 beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
16 beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
17
18 // BeanFactory接口未在普通工厂中注册可解析类型
19 // 注册可以解析的自动装配,我们能直接在任何组件中自动注入
20 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
21 beanFactory.registerResolvableDependency(ResourceLoader.class, this);
22 beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
23 beanFactory.registerResolvableDependency(ApplicationContext.class, this);
24
25 // 注册早期的后处理器,以便将内部bean检测为applicationlisteners。
26 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
27
28 // 添加编译时的 AspectJ
29 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
30 beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
31 // 为类型匹配设置临时类加载器。
32 beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
33 }
34
35 // 给 beanfactory 中注册能用的一些组件。
36 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
37 beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
38 }
39 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
40 beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
41 }
42 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
43 beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
44 }
45 }

【4】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 }

【4.1】invokeBeanFactoryPostProcessors 源码分析

1 public static void invokeBeanFactoryPostProcessors(
2 ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {
3
4 // 如果有,请先调用BeanDefinitionRegistryPostProcessors。
5 Set processedBeans = new HashSet<>();
6 //当前的 beanFactory == BeanDefinitionRegistry
7 if (beanFactory instanceof BeanDefinitionRegistry) {
8 BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
9 List regularPostProcessors = new ArrayList<>();
10 List registryProcessors = new ArrayList<>();
11 //获取所有的 BeanFactoryPostProcessor
12 for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
13 if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
14 BeanDefinitionRegistryPostProcessor registryProcessor =
15 (BeanDefinitionRegistryPostProcessor) postProcessor;
16 registryProcessor.postProcessBeanDefinitionRegistry(registry);
17 registryProcessors.add(registryProcessor);
18 }
19 else {
20 regularPostProcessors.add(postProcessor);
21 }
22 }
23
24 // 首先执行实现了 priority 接口的后置处理器
25 String[] postProcessorNames =
26 beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
27 for (String ppName : postProcessorNames) {
28 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
29 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
30 processedBeans.add(ppName);
31 }
32 }
33 //限制性实现了 priorityOrdered 优先级接口的后置处理器
34 sortPostProcessors(currentRegistryProcessors, beanFactory);
35 registryProcessors.addAll(currentRegistryProcessors);
36 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
37 currentRegistryProcessors.clear();
38
39 // 接下来,调用实现ordered接口的后置处理器
40 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
41 for (String ppName : postProcessorNames) {
42 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
43 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
44 processedBeans.add(ppName);
45 }
46 }
47 sortPostProcessors(currentRegistryProcessors, beanFactory);
48 registryProcessors.addAll(currentRegistryProcessors);
49 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
50 currentRegistryProcessors.clear();
51
52 // 最后,调用所有其他没有实现任何接口的后置处理器
53 boolean reiterate = true;
54 while (reiterate) {
55 reiterate = false;
56 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
57 for (String ppName : postProcessorNames) {
58 if (!processedBeans.contains(ppName)) {
59 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
60 processedBeans.add(ppName);
61 reiterate = true;
62 }
63 }
64 sortPostProcessors(currentRegistryProcessors, beanFactory);
65 registryProcessors.addAll(currentRegistryProcessors);
66 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
67 currentRegistryProcessors.clear();
68 }
69
70 // 现在,调用到目前为止处理的所有处理器的postprocessebeanfactory回调。
71 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
72 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
73 }
74
75 else {
76 // 调用使用上下文实例注册的工厂处理器。
77 invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
78 }
79
80 // 不要在这里初始化factorybeans:我们需要保留所有常规bean
81 // 获取所有的的后置处理器
82 //后续操作与前面相同,查看是否实现了priority、order接口和获取全部
83 String[] postProcessorNames =
84 beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
85
86 // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
87 // Ordered, and the rest.
88 List priorityOrderedPostProcessors = new ArrayList<>();
89 List orderedPostProcessorNames = new ArrayList<>();
90 List nonOrderedPostProcessorNames = new ArrayList<>();
91 for (String ppName : postProcessorNames) {
92 if (processedBeans.contains(ppName)) {
93 // skip - already processed in first phase above
94 }
95 else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
96 priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
97 }
98 else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
99 orderedPostProcessorNames.add(ppName);
100 }
101 else {
102 nonOrderedPostProcessorNames.add(ppName);
103 }
104 }
105
106 // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
107 sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
108 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
109
110 // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
111 List orderedPostProcessors = new ArrayList<>();
112 for (String postProcessorName : orderedPostProcessorNames) {
113 orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
114 }
115 sortPostProcessors(orderedPostProcessors, beanFactory);
116 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
117
118 // Finally, invoke all other BeanFactoryPostProcessors.
119 List nonOrderedPostProcessors = new ArrayList<>();
120 for (String postProcessorName : nonOrderedPostProcessorNames) {
121 nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
122 }
123 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
124
125 // Clear cached merged bean definitions since the post-processors might have
126 // modified the original metadata, e.g. replacing placeholders in values…
127 beanFactory.clearMetadataCache();
128 }

【5】registerBeanPostProcessors 源码展示:注册BeanPostProcessor,不同的接口类型的 BeanPostProcessor;在bean 创建前后的执行时机是不一样的。
  ■  BeanPostProcessor:
  ■  DestructionAwareBeanPostProcessor
  ■  InstantiationAwareBeanPostProcessor
  ■  SmartInstantiationAwareBeanPostProcessor
  ■  MergedBeanDefinitionPostProcessor【internalPostProcessors】:优先记录:1

1 protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
2 //方法实现在外层
3 PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
4 }
5
6 public static void registerBeanPostProcessors(
7 ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
8 //获取所有的 bean后置处理器
9 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
10
11 // 检查和统计后置处理器
12 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
13 beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
14
15 // bean 的后置处理器也有实现 priority和order接口的后置处理器,用来指定优先级
16 List priorityOrderedPostProcessors = new ArrayList<>();
17 List internalPostProcessors = new ArrayList<>();
18 List orderedPostProcessorNames = new ArrayList<>();
19 List nonOrderedPostProcessorNames = new ArrayList<>();
20 for (String ppName : postProcessorNames) {
21 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
22 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
23 priorityOrderedPostProcessors.add(pp);
24 //将实现了 MergedBeanDefinitionPostProcessor 接口的后置处理器加入到internalPostProcessors
25 if (pp instanceof MergedBeanDefinitionPostProcessor) {
26 internalPostProcessors.add(pp);
27 }
28 }
29 else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
30 orderedPostProcessorNames.add(ppName);
31 }
32 else {
33 nonOrderedPostProcessorNames.add(ppName);
34 }
35 }
36
37 // 首先,注册实现priorityordered接口的beanPostProcessors。
38 sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
39 //注册bean后置处理器到beanFactory
40 //beanFactory.addBeanPostProcessor(postProcessor);
41 registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
42
43 // 接下来,注册实现ordered接口的beanPostProcessors。
44 List orderedPostProcessors = new ArrayList<>();
45 for (String ppName : orderedPostProcessorNames) {
46 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
47 orderedPostProcessors.add(pp);
48 if (pp instanceof MergedBeanDefinitionPostProcessor) {
49 internalPostProcessors.add(pp);
50 }
51 }
52 sortPostProcessors(orderedPostProcessors, beanFactory);
53 registerBeanPostProcessors(beanFactory, orderedPostProcessors);
54
55 // 现在,注册所有常规beanpstprocessors。
56 List nonOrderedPostProcessors = new ArrayList<>();
57 for (String ppName : nonOrderedPostProcessorNames) {
58 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
59 nonOrderedPostProcessors.add(pp);
60 if (pp instanceof MergedBeanDefinitionPostProcessor) {
61 internalPostProcessors.add(pp);
62 }
63 }
64 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
65
66 // 最后,重新注册所有内部 beanpstprocessors。实现了 MergedBeanDefinitionPostProcessor 接口的后置处理器
67 sortPostProcessors(internalPostProcessors, beanFactory);
68 registerBeanPostProcessors(beanFactory, internalPostProcessors);
69
70 // 注册一个ApplicationListenerDetector 来检查bean创建完成是否为侦听器,如果是将此bean 放入到容器中
71 // 将其移动到处理器链的末端(用于获取代理等)。
72 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
73 }

【6】initMessageSource 源码解析:

1 protected void initMessageSource() {
2 //获取 bean工厂
3 ConfigurableListableBeanFactory beanFactory = getBeanFactory();
4 //查看beanFactory 中是否有 messsource 类型组件,有则赋值给messageSource
5 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
6 this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
7 if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
8 HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
9 if (hms.getParentMessageSource() == null) {
10 hms.setParentMessageSource(getInternalParentMessageSource());
11 }
12 }
13 if (logger.isTraceEnabled()) {
14 logger.trace("Using MessageSource [" + this.messageSource + "]");
15 }
16 }
17 //不存在则创建一个 messageSource 主要作用:从配置文件中取出国际化等的值
18 else {
19 DelegatingMessageSource dms = new DelegatingMessageSource();
20 dms.setParentMessageSource(getInternalParentMessageSource());
21 this.messageSource = dms;
22 //将messageSource 注入到容器中
23 beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
24 if (logger.isTraceEnabled()) {
25 logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
26 }
27 }
28 }

【7】initApplicationEventMulticaster 初始化事件派发器,源码分析:

1 protected void initApplicationEventMulticaster() {
2 //获取 BeanFactory
3 ConfigurableListableBeanFactory beanFactory = getBeanFactory();
4 //从beanFactory 中获取 applicationEventMulticaster 的事件派发器
5 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
6 this.applicationEventMulticaster =
7 beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
8 if (logger.isTraceEnabled()) {
9 logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
10 }
11 }
12 //否则创建一个简单的事件派发器 SimpleApplicationEventMulticaster
13 else {
14 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
15 //并注册到容器中,以后其他组件直接注入。
16 beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
17 if (logger.isTraceEnabled()) {
18 logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
19 "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
20 }
21 }
22 }

【8】registerListeners 源码分析:

1 protected void registerListeners() {
2 // 首先注册静态指定的侦听器。
3 for (ApplicationListener listener : getApplicationListeners()) {
4 //将监听器添加到事件派发器中
5 getApplicationEventMulticaster().addApplicationListener(listener);
6 }
7
8 // 重容器中获取所有的 ApplicationListener
9 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
10 for (String listenerBeanName : listenerBeanNames) {
11 //添加到监听器事件派发器中
12 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
13 }
14
15 // 派发之前步骤产生的事件
16 Set earlyEventsToProcess = this.earlyApplicationEvents;
17 this.earlyApplicationEvents = null;
18 if (earlyEventsToProcess != null) {
19 for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
20 getApplicationEventMulticaster().multicastEvent(earlyEvent);
21 }
22 }
23 }

【9】初始化所有剩下的单实例bean 的方法 finishBeanFactoryInitialization(beanFactory); 源码展示:

1 protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
2 // 初始化上下文的转换服务。 (过)
3 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
4 beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
5 beanFactory.setConversionService(
6 beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
7 }
8
9 // 如果没有bean后处理器,则注册默认的嵌入式值解析器 (过)
10 // (例如propertyplaceholderconfigurer bean)在以下任何时间之前注册:
11 // 此时,主要用于注释属性值中的分辨率。
12 if (!beanFactory.hasEmbeddedValueResolver()) {
13 beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
14 }
15
16 // 尽早初始化loadTimeWeaveraware bean,以便尽早注册其转换器。 (过)
17 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
18 for (String weaverAwareName : weaverAwareNames) {
19 getBean(weaverAwareName);
20 }
21
22 // 停止使用临时类加载器进行类型匹配。 (过)
23 beanFactory.setTempClassLoader(null);
24
25 // 允许缓存所有bean定义元数据,不需要进一步更改。 (过)
26 beanFactory.freezeConfiguration();
27
28 // *****实例化所有剩余的(非延迟初始化)单例。***
29 beanFactory.preInstantiateSingletons();
30 }

【9.1】实例化所有剩余的(非延迟初始化)单例。beanFactory.preInstantiateSingletons() 方法源码如下:

1 @Override
2 public void preInstantiateSingletons() throws BeansException {
3 if (logger.isTraceEnabled()) {
4 logger.trace("Pre-instantiating singletons in " + this);
5 }
6
7 // 获取所有bean的定义信息
8 List beanNames = new ArrayList<>(this.beanDefinitionNames);
9
10 // 所有非惰性单例bean的触发器初始化…
11 for (String beanName : beanNames) {
12 //获取bean的定义信息
13 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
14 //判断不是抽象的、是单实例的、不是懒加载的则创建
15 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
16 //判断是否为 Factorybean:是否是实现了factoryBean接口的,通过getObject 获取实例
17 if (isFactoryBean(beanName)) {
18 Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
19 if (bean instanceof FactoryBean) {
20 final FactoryBean factory = (FactoryBean) bean;
21 boolean isEagerInit;
22 if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
23 isEagerInit = AccessController.doPrivileged((PrivilegedAction)
24 ((SmartFactoryBean) factory)::isEagerInit,
25 getAccessControlContext());
26 }
27 else {
28 isEagerInit = (factory instanceof SmartFactoryBean &&
29 ((SmartFactoryBean) factory).isEagerInit());
30 }
31 if (isEagerInit) {
32 getBean(beanName);
33 }
34 }
35 }
36 /**如果不是工厂bean——>getBean(beanName)---> doGetBean()--->获取缓存中保存的单实例Bean,如果能
37 *singletonObjects.get(beanName); Map singletonObjects用来缓存所有的单实例bean
38 *-->缓存中获取不到,则创建对象:1、先标记当前bean 被创建(防止多线程)2、获取bean的定义信息
39 *3、获取当前bean依赖的其他bean(dependsOn),如果有按照getBean的方式,将依赖的bean先创建出来
40 *4、启动单实例bean的创建流程:通过beanFactory.getObject创建——>内部调用createBean创建bean——>
41 *拿到bean的定义信息,调用resolveBeforeInstantiation(beanName,mbdToUse):让beanPoseProcess提前
42 *拦截获取代理对象的机会。InstantiationAwareBeanPostProcessor:提前执行,
43 *先触发postProcessBeforeInstantiation();如果有返回值则触发postProcessAfterInitalization()
44 *如果没有返回代理对象,则执行 doCreateBean(beanName,mbdToUse,args)创建bean。
45 *创建bean的流程:
46 * 1)、createBeanInstance(beanName,mbdToUse,args)进入此方法:
47 * 1.1)通过工厂方法或者执行构造器解析执行即可:创建的对象是个空对象
48 * 2)、applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);调用
49 * MergedBeanDefinitionPostProcessor的bdp.postProcessMergedBeanDefinition(mbd,beanType,beanName)
50 * 3)、给bean实例赋值,populateBean(beanName,mbd,bw,pvs) 获取所有的属性信息,赋值之前获取所有的 InstantiationAwareBeanPostProcessor 后置处理器的postProcessAfterInstantiation()
51 * 第二次获取InstantiationAwareBeanPostProcessor后置处理器;执行 postProcessPropertyValues()
52 * 最后为应用 Bean属性赋值:为属性利用 setter 方法进行赋值 applyPropertyValues(beanName,mbd,bw,pvs)
53 * 4)、bean 初始化:initializeBean(beanName,bean,mbd)
54 * ①、执行xxxAware接口的方法,调用实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口的方法。
55 * ②、执行后置处理器之前的方法:applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)
56 * 所有后置处理器的 BeanPostProcessor.postProcessBeforeInitialization()
57 * ③、执行初始化方法:invokeInitMethods(beanName, wrappedBean, mbd);
58 * 先判断是否实现了InitializingBean接口的实现;执行接口规定的初始化。
59 * 其次自定义初始化方法。
60 * ④、applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);执行初始化之后的后置处理器的方法。
61 * BeanPostProcessor.postProcessAfterInitialization(result, beanName);
62 * 5)、注册bean的销毁方法到容器中registerDisposableBeanIfNecessary(beanName, bean, mbd);
63 *
64 *5、将创建的bean 添加到缓存中singleObject(Map);其实IOC容器就是这些Map集合,很多Map里面保存了单实例Bean,环境信息等等。。。
65 **/
66 else {
67 getBean(beanName);
68 }
69 }
70 }
71 }

【9.2】所有Bean 都利用getBean 创建完成之后,检查所有的 Bean是否实现了 SmartInitializingSingleton 接口,如果是,就执行 smartSingleton.afterSingletonsInstantiated();

1 for (String beanName : beanNames) {
2 Object singletonInstance = getSingleton(beanName);
3 if (singletonInstance instanceof SmartInitializingSingleton) {
4 final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
5 if (System.getSecurityManager() != null) {
6 AccessController.doPrivileged((PrivilegedAction) () -> {
7 smartSingleton.afterSingletonsInstantiated();
8 return null;
9 }, getAccessControlContext());
10 }
11 else {
12 smartSingleton.afterSingletonsInstantiated();
13 }
14 }
15 }

【10】finishRefresh:最后一步,完成 BeanFactory 的初始化创建工作;IOC容器创建完成。
用户可以实现 LifecycleProcessor 接口,可以在 BeanFactory 执行 void onRefresh(); 和 void onClose();时调用。默认从容器中找是否有 LifecycleProcessor  的组件。如果没有则创建一个默认的声明周期组件:new DefaultLifecycleProcessor();并注册到beanFactory 容器中。

1 protected void finishRefresh() {
2 // 清除上下文级资源缓存(例如扫描中的asm元数据)。
3 clearResourceCaches();
4 // 初始化与生命周期有关的后置处理器
5 initLifecycleProcessor();
6 //获取前面定义的声明周期处理器(BeanFactory)并调用回调方法 onRefresh
7 getLifecycleProcessor().onRefresh();
8 // 发布容器刷新完成事件
9 publishEvent(new ContextRefreshedEvent(this));
10
11 // 不重要。。。
12 LiveBeansView.registerApplicationContext(this);
13 }


1)、Spring 容器在启动的时候,先会保存所有注册来的 Bean 的定义信息;
    ■  Xml 注册bean:
    ■  注解注册Bean:@Service、@Component、@Bean等等
2)、Spring 容器会在合适的时机创建 bean;
    ■  用到这个 bean 的时候,利用 getBean 创建 bean ,创建好后保存在容器中。
    ■  统一创建剩下所有bean 的时候,调用 finishBeanFactoryInitialization()
3)、后置处理器:BeanPostProcessor:每一个 bean 的创建完成,都会使用各种后置处理器进行处理,来增强bean 的功能:
    ■  AutowriteAnnotationBeanPostProcessor:处理自动注入;
    ■  AnnotationAwareAspectJAutoProxyCreator:来做AOP 功能;等等。。。
4)、事件驱动模型:ApplicationListener 事件监听。ApplicationEventMulticaster 事件派发。

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器