Spring容器创建过程源码解读

本节我们来通过源码的方式来走一圈我们IOC容器创建的流程,其实不难发现我们采用注解开发,会采用AnnotationConfigApplicationContext作为【容器】,这整个的核心都在#refresh()此方法中完成,那么我们接下来的核心就是此方法
refresh
该方法位于AbstractApplication中,我们容器的创建都是方法#refresh()完成,分别来看
  • 1、this.prepareRefresh()
该方法的主要目的是我们容器刷新前的一些预处理准备过程,进去看都做了那些准备
1.1. 首先通过方法this.initPropertySources()来初始化一些属性的设置
protected void initPropertySources() { }

可见方法initPropertySources可以由我们实现定制一些个性化的属性设置,我们发现
1.2. 接着是通过方法#this.getEnvironment().validateRequiredProperties()来做一些属性合法的检验过程。
1.3. 通过方法 this.earlyApplicationEvents = new LinkedHashSet()来保存容器中一些早期的事件
上述就是方法#prepareRefresh()预处理的一些准备工作,接着看
  • 2.this.obtainFreshBeanFactory()
该方法的主要目的是来获取一个BeanFactory对象,其真实类型为【ConfigurableListableBeanFactory】,进去看是如何来获取的过程
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { this.refreshBeanFactory(); return this.getBeanFactory(); }

  • 2.1.在方法#obtainFreshBeanFactory() 中我们可以看到的是通过 this.refreshBeanFactory()方法刷新BeanFactory【实际上是创建beanFactory对象】,通过Dbug我们来到GenericApplicationContext#refreshBeanFactory(),代码如下:
protected final void refreshBeanFactory() throws IllegalStateException { if (!this.refreshed.compareAndSet(false, true)) { throw new IllegalStateException("GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once"); } else { this.beanFactory.setSerializationId(this.getId()); } }

Spring容器创建过程源码解读
文章图片
image.png
从截图来看这里为我们创建的是一个【DefaultListableBeanFactory 】类型的BeanFactory,具体创建过程如下:
public GenericApplicationContext() { this.customClassLoader = false; this.refreshed = new AtomicBoolean(); this.beanFactory = new DefaultListableBeanFactory(); }

通过GenericApplicationContext类的无参构造器直接帮我们来newDefaultListableBeanFactory();
同时给它设置id
  • 2.2. 将创建的BeanFactory【DefaultListableBeanFactory】通过方法this.getBeanFactory()直接返回
3、this.prepareBeanFactory(beanFactory)
该方法主要的目的是对前面创建的BeanFactory【DefaultListableBeanFactory】进行相关的设置,具体我们通过Dbug跟踪代码来到AbstractApplication#prepareBeanFactory(beanFactory)方法:
  • 3.1. 通过如下操作给BeanFactory设置类加载器
beanFactory.setBeanClassLoader(this.getClassLoader());

  • 3.2. 通过如下操作给BeanFactory设置表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

  • 3.3.通过如下操作给BeanFactory添加属性编辑注册器
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));

  • 3.4.通过如下操作给BeanFactory添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

  • 3.5.通过如下操作给BeanFactory设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

  • 3.6. 通过如下操作给BeanFactory设置注册可以解析的自动装配;我们能直接在任何组件中自动注入:BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);

  • 3.7. 添加BeanPostProcessor【ApplicationListenerDetector】
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

4、this.postProcessBeanFactory(beanFactory)
该方法主要的目的是在BeanFactory准备工作完成之后进行相关的后置处理操作,方法进去:
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { }

我们发现是空实现,我们可以通过重写此方法对BeanFactory创建并预准备完成以后做进一步的设置
5、this.invokeBeanFactoryPostProcessors(beanFactory)
该方法主要的目的是来执行BeanFactoryPostProcessor的#postProcessBeanFactory(beanFactory)方法,之前我们也说过BeanFactoryPostProcessor是针对于BeanFactory的后置处理器,其在beanFactory标准初始化之后来执行此方法,具体过程通过Dbug来跟踪代码来到PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors)方法
  • 5.1. 首先是先来执行BeanDefinitionRegistryPostProcessor的方法
  1. 首先获取所有的获取所有的BeanDefinitionRegistryPostProcessor
  2. 其次是先来处理实现了PriorityOrdered【优先级接口】的BeanDefinitionRegistryPostProcessor的类
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); }

3.接着是执行BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(registry)方法
4.最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors
上述BeanDefinitionRegistryPostProcessors执行完成之后,接着是来执行我们的BeanFactoryPostProcessor的方法
  1. 首先是获取所有的BeanFactoryPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

2.接着是遍历处理postProcessorNames
  • 2.1.如果实现了PriorityOrdered【优先级】接口,进行相关处理
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { regularPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));

  • 2.1.2. 接着是调用BeanFactoryPostProcessor#postProcessBeanFactory(beanFactory)方法进行相关的设置
  • 2.2.如果实现了Ordered【顺序】接口,进行相关处理
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { registryProcessors.add(ppName);

  • 2.2.1.接着同样来调用#postProcessBeanFactory(beanFactory)来进行相关的处理
while(var21.hasNext()) { String postProcessorName = (String)var21.next(); orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); }sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors((Collection)orderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);

  • 2.3. 如果是即没有实现PriorityOrdered接口和Ordered接口,同样进行相关的处理
else { currentRegistryProcessors.add(ppName); }

  • 2.3.1. 接着同样来调用#postProcessBeanFactory(beanFactory)来进行相关的处理
while(var24.hasNext()) { ppName = (String)var24.next(); nonOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); }invokeBeanFactoryPostProcessors((Collection)nonOrderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory); beanFactory.clearMetadataCache(); }

上述就是整个this.invokeBeanFactoryPostProcessors(beanFactory)的过程,其实质不是很难,感兴趣的可以Dbug跟踪下代码就知道了
6、 this.registerBeanPostProcessors(beanFactory)
该方法的主要目的是注册BeanPostProcess【bean的后置处理器】,我们通过它来拦截bean的创建,然后进行相关的设置操作,当然不同的类型的【BeanPostProcessor】的执行的时机是不同的如:
  • beanPostProcessor:在bean的初始化前后进行相关的操作
  • InstantiationAwareBeanPostProcessor :在Aop和声明式事务中,我们利用 【InstantiationAwareBeanPostProcessor 】后置处理器帮我们进行代理对象的封装等操作
上述是我们最近学习中用到的,其后置处理器的种类是很多的如:DestructionAwareBeanPostProcessor、MergedBeanDefinitionPostProcessor【internalPostProcessors】、SmartInstantiationAwareBeanPostProcessor等,接着回到我们的方法中,Dbug跟踪代码来到PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)方法:
  • 6.1. 首先通过bean的类型获取所有的后置处理器的name【postProcessorNames】
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

  • 6.2. 首先来注册实现了PriorityOrdered【优先级】接口的BeanPostProcessor
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); ....... sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, (List)priorityOrderedPostProcessors);

  • 6.3. 接着是来注册实现了Ordered接口的后置处理器
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); ....... List orderedPostProcessors = new ArrayList(orderedPostProcessorNames.size()); Iterator var14 = orderedPostProcessorNames.iterator(); while(var14.hasNext()) { String ppName = (String)var14.next(); BeanPostProcessor pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, (List)orderedPostProcessors);

  • 6.4.最后注册没有实现任何排序接口的后置处理器
else { nonOrderedPostProcessorNames.add(ppName); }List nonOrderedPostProcessors = new ArrayList(nonOrderedPostProcessorNames.size()); Iterator var17 = nonOrderedPostProcessorNames.iterator(); while(var17.hasNext()) { ppName = (String)var17.next(); pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } }registerBeanPostProcessors(beanFactory, (List)nonOrderedPostProcessors); sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, (List)internalPostProcessors);

  • 6.5. 最后给beanFactory添加ApplicationListenerDetector,其主要的目的是在bean创建完成之后检测是否是ApplicationListener
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));

7、this.initMessageSource()
该方法主要的目的是初始化MessageSource组件,其主要包括:做国际化功能、消息绑定、消息解析
  • 7.1. 首先是获取beanFactory实例
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();

  • 7.2.接着是看容器中是否存在id为messageSource类型为MessageSource组件,存在的话进行赋值操作,不存在的话创建一个DelegatingMessageSource
if (beanFactory.containsLocalBean("messageSource")) { this.messageSource = (MessageSource)beanFactory.getBean("messageSource", MessageSource.class); if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource)this.messageSource; if (hms.getParentMessageSource() == null) { hms.setParentMessageSource(this.getInternalParentMessageSource()); } }

  • 7.3. 将创建好的MessageSource组件注册到容器中,以便后面直接使用
DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(this.getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton("messageSource", this.messageSource); if (this.logger.isTraceEnabled()) { this.logger.trace("No 'messageSource' bean, using [" + this.messageSource + "]"); } }

Spring容器创建过程源码解读
文章图片
image.png 8、this.initApplicationEventMulticaster()
上述方法的主要的作用是初始化事件配发 器,通过Dbug来跟踪下代码来到AbstractApplicationContext#initApplicationEventMulticaster()方法:
  • 8.1. 首先是获取BeanFactory实例
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();

Spring容器创建过程源码解读
文章图片
image.png
  • 8.2. 从容器中获取id为applicationEventMulticaster类型ApplicationEventMulticaster的组件,如果能获取到赋值给this.applicationEventMulticaster
if (beanFactory.containsLocalBean("applicationEventMulticaster")) { this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class); if (this.logger.isTraceEnabled()) { this.logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); }

  • 8.3. 如果从容器中没有拿到,则创建一个SimpleApplicationEventMulticaster,同时将创建的SimpleApplicationEventMulticaster组件以key为【applicationEventMulticaster】,value 为【this.applicationEventMulticaster】也就是具体的事件配发器实例注册进容器中
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster); if (this.logger.isTraceEnabled()) { this.logger.trace("No 'applicationEventMulticaster' bean, using [" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); }

Spring容器创建过程源码解读
文章图片
spring IOC源码分析3.png 9、this.onRefresh()
上述此方法实际上是留给子类来实现的,子类可以重新此方法在容器刷新时自定义自己的逻辑,具体代码如下:
protected void onRefresh() throws BeansException { }

10、 this.registerListeners()
上述的方法主要的目的是将所有的ApplicationListener注册进容器,我们通过Dbug来跟踪下代码来到AbstractApplica事件petionContext#registerListeners()方法中
  • 10.1. 通过类型获取到所有的监听器的名字【listenerBeanNames】
String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);

  • 10.2. 将每一个监听器遍历添加到事件配发器中【ApplicationEventMulticaster】
String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false); String[] var7 = listenerBeanNames; int var3 = listenerBeanNames.length; for(int var4 = 0; var4 < var3; ++var4) { String listenerBeanName = var7[var4]; this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); }

  • 10.3.配发之前步骤产生的事件【earlyEventsToProcess】
Set earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { Iterator var9 = earlyEventsToProcess.iterator(); while(var9.hasNext()) { ApplicationEvent earlyEvent = (ApplicationEvent)var9.next(); this.getApplicationEventMulticaster().multicastEvent(earlyEvent); } }

Spring容器创建过程源码解读
文章图片
image.png
【Spring容器创建过程源码解读】很显然我们这里目前是没有事件产生的
11、this.finishBeanFactoryInitialization(beanFactory)
该方法的主要作用是初始化所有剩下的单实例bean,这里泛指我们自己定义的bean,通过Dbug我们来到AbstractApplicationContext#finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)方法中,我们来看:
方法前面的都是为单实例bean创建的环境准备以及是否实现了Aware接口处理,其中最主要的方法入口为:
beanFactory.preInstantiateSingletons();

我们Dbug跟踪代码来到DefaultListableBeanFactory#preInstantiateSingletons()方法
  • 11.1.首先是获取容器中所有的bean【beanNames】,然后while循环依次创建 和初始化操作
Spring容器创建过程源码解读
文章图片
image.png
上图中就是当前容器中获取到的所有bean的定义的name,接着看:
  • 11.2.获取当前要创建和初始化bean的定义信息【BeanDefinition】
bd = this.getMergedLocalBeanDefinition(beanName);

Spring容器创建过程源码解读
文章图片
image.png
  • 11.3. 对当前要创建的bean进行判断如:是否是抽象的、是否不是单实例和是否是懒加载以及是否是一个FactoryBean类型的bean
...省略部分代码... while(bd.isAbstract()); } while(!bd.isSingleton()); } while(bd.isLazyInit()); if (this.isFactoryBean(beanName)) { bean = this.getBean("&" + beanName); break; }

不是FactoryBean类型的bean的话,利用this.getBean(beanName)来创建对象接着来到AbstractBeanFactory#getBean(String name)方法
public Object getBean(String name) throws BeansException { return this.doGetBean(name, (Class)null, (Object[])null, false); }

其核心逻辑在方法#doGetBean(...)里进行了实现,我们继续跟踪代码:
  • 11.3.1. 首先通过去别名的方式来获取bean的name值,代码如下:
String beanName = this.transformedBeanName(name);

Spring容器创建过程源码解读
文章图片
image.png
  • 11.3.2.通过在上面的name值从缓存中去获取该bean实例,如果能获取到说明之前完成了创建
Object sharedInstance = this.getSingleton(beanName);

Spring容器创建过程源码解读
文章图片
image.png
很显然我们没有获取到,那么接下来走创建的过程,接着看
  • 11.3.3. 判断当前bean是否正在创建中,如果是直接抛BeanCurrentlyInCreationException异常
if (this.isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); }

  • 11.3.4. 获取父类beanFactory,如果父类BeanFactory不为null且不包含当前bean的定义信息【BeanDefinition】,且父BeanFactorey是抽象BeanFactory,我们进行bean的创建
BeanFactory parentBeanFactory = this.getParentBeanFactory(); if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) { String nameToLookup = this.originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory)parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly); }

Spring容器创建过程源码解读
文章图片
image.png
很显然当前父BeanFactory为null,所以我们接着看:
  • 11.3.5.标记当前bean已经被创建
if (!typeCheckOnly) { this.markBeanAsCreated(beanName); }

  • 11.3.6.检查当前bean是否依赖于其他的bean,如果是,先创建当前当前bean所依赖的bean
RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName); this.checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn(); String[] var11; if (dependsOn != null) { var11 = dependsOn; int var12 = dependsOn.length; for(int var13 = 0; var13 < var12; ++var13) { String dep = var11[var13]; if (this.isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); }this.registerDependentBean(dep, beanName); try { this.getBean(dep); } catch (NoSuchBeanDefinitionException var24) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", var24); } } }

  • 11.3.7.上述都不成立的话,接下来是创建bean的真正入口:
if (mbd.isSingleton()) { sharedInstance = this.getSingleton(beanName, () -> { try { return this.createBean(beanName, mbd, args); } catch (BeansException var5) { this.destroySingleton(beanName); throw var5; } });

继续跟踪代码来到AbstractAutowireCapableBeanFactory#createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)方法
11.3.8.其中方法就是在bean创建之前利用BeanPostProcessor来拦截返回代理对象
beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse)

也就是我们的InstantiationAwareBeanPostProcessor在这里提前执行了我们的方法#postProcessBeforeInstantiation(),如果有返回的代理对象【bean】之后触发postProcessAfterInitialization()方法
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) { Class targetType = this.determineTargetType(beanName, mbd); if (targetType != null) { bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName); } } }mbd.beforeInstantiationResolved = bean != null; }return bean; }

上述过程并没有代理对象bean返回时,我们走下面的流程
  • 11.3.9. 接着通过方法#doCreateBean(...)完成bean的真正创建过程
  • 11.3.10. 首先是bean实例的创建过程:
if (instanceWrapper == null) { instanceWrapper = this.createBeanInstance(beanName, mbd, args); }

创建实例的过程是利用工厂方法或者对象的构造器创建出Bean实例,接着看:
  • 11.3.11. 通过调用MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition(mbd, beanType, beanName)方法对bean进行相关的设置
  • 11.3.12. 给bean进行属性的装备
this.populateBean(beanName, mbd, instanceWrapper)

  • 11.3.13.进行bean的初始化操作
exposedObject = this.initializeBean(beanName, exposedObject, mbd)

  • 11.3.14. 首先通过方法invokeAwareMethods(beanName, bean)执行各种实现了Aware接口的方法,代码如下:
private void invokeAwareMethods(String beanName, Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware)bean).setBeanName(beanName); }if (bean instanceof BeanClassLoaderAware) { ClassLoader bcl = this.getBeanClassLoader(); if (bcl != null) { ((BeanClassLoaderAware)bean).setBeanClassLoader(bcl); } }if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware)bean).setBeanFactory(this); } }}

  • 11.3.14.1.接着【执行后置处理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)
Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); }

  • 11.3.14.2.接着通过方法this.invokeInitMethods(beanName, wrappedBean, mbd)完成bean的初始化,进去看看
  • 11.3.14.3.首先判断当前bean是否实现了InitializingBean接口
boolean isInitializingBean = bean instanceof InitializingBean;

如果是的话执行InitializingBean接口的afterPropertiesSet完成bean的实例化
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (this.logger.isTraceEnabled()) { this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); }if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(() -> { ((InitializingBean)bean).afterPropertiesSet(); return null; }, this.getAccessControlContext()); } catch (PrivilegedActionException var6) { throw var6.getException(); } } else { ((InitializingBean)bean).afterPropertiesSet(); } }

  • 11.3.14.4.如果是自定义初始化方法的话,通过方法#this.invokeCustomInitMethod(beanName, bean, mbd)完成bean的实例化
上述就是初始化的过程
  • 11.3.15. 执行后置处理器初始化之applyBeanPostProcessorsAfterInitialization
if (mbd == null || !mbd.isSynthetic()) { wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); }

  • 11.3.16. 接着是向容器中注册bean的销毁方法
this.registerDisposableBeanIfNecessary(beanName, bean, mbd);

  • 11.3.17.最后将我们创建的bean实例返回并进行缓存
# DefaultSingletonBeanRegistry this.addSingleton(beanName, singletonObject);

12、this.finishRefresh()
该方法表示我们完成BeanFactory的初始化创建工作,也就是IOC容器就创建完成,Dbug跟踪代码来到AbstractApplicationContext#finishRefresh()方法
  • 12.1. 首先是清空资源缓存
this.clearResourceCaches()

  • 12.2. 接着是初始化生命周期有关的后置处理器【LifecycleProcessor】
this.initLifecycleProcessor();

跟踪代码来到:
  • 12.2.1. 首先获取BeanFactory实例
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();

  • 12.2.2. 接着从容器中获取id为lifecycleProcessor类型为【LifecycleProcessor】的组件,如果获取到了直接赋值给this.lifecycleProcessor
if (beanFactory.containsLocalBean("lifecycleProcessor")) { this.lifecycleProcessor = (LifecycleProcessor)beanFactory.getBean("lifecycleProcessor", LifecycleProcessor.class); if (this.logger.isTraceEnabled()) { this.logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]"); }

  • 12.2.3.如果没有获取到直接创建一个DefaultLifecycleProcessor,并将它注册进容器中
else { DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor(); defaultProcessor.setBeanFactory(beanFactory); this.lifecycleProcessor = defaultProcessor; beanFactory.registerSingleton("lifecycleProcessor", this.lifecycleProcessor); if (this.logger.isTraceEnabled()) { this.logger.trace("No 'lifecycleProcessor' bean, using [" + this.lifecycleProcessor.getClass().getSimpleName() + "]"); } }

  • 12.3. 通过获取到上述创建的【LifecycleProcessor】处理器来回调onRefresh()方法
this.getLifecycleProcessor().onRefresh();

  • 12.4. 通过如下操作来发布容器刷新操作事件
this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this)));

Spring容器创建过程源码解读
文章图片
image.png
  • 12.5.最后进行如下的操作
LiveBeansView.registerApplicationContext(this);

上述就是Spring创建容器的过程

    推荐阅读