01|Bean的初始化

1、AbstractApplicationContext

Spring管理的所有的非懒加载的单例Bean会随着容器的初始化加载到容器中,初始化入口依旧在AbstractApplicationContext的refresh方法中

  1. public abstract class AbstractApplicationContext extends DefaultResourceLoader
  2. implements ConfigurableApplicationContext {
  3. @Override
  4. public void refresh() throws BeansException, IllegalStateException {
  5. synchronized (this.startupShutdownMonitor) {
  6. // 代码略...
  7. // 1.1、实例化并调⽤实现了BeanFactoryPostProcessor接⼝的Bean
  8. // 会扫描注册Bean的元数据信息并存入BeanFactory的beanDefinitionNames中
  9. // Spring会将需要创建的Bean的信息封装到BeanDefinition类中,其中包含的类的所有元数据信息,如类的全路径名、声明周期等等
  10. invokeBeanFactoryPostProcessors(beanFactory);
  11. // 代码略...
  12. // 1.2、依据1.1中的Bean元数据信息实例话所有非懒加载的单例bean
  13. finishBeanFactoryInitialization(beanFactory);
  14. // 代码略...
  15. }
  16. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  17. // 调用DefaultListableBeanFactory的preInstantiateSingletons方法进行开始Bean的创建
  18. beanFactory.preInstantiateSingletons();
  19. }
  20. }

2、DefaultListableBeanFactory

DefaultListableBeanFactory的preInstantiateSingletons方法中会遍历注册到beanFactory的Bean信息进行对象的逐一创建

  1. public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
  2. implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
  3. @Override
  4. public void preInstantiateSingletons() throws BeansException {
  5. // 代码略...
  6. // 此处先不关注其余代码,只看getBean方法
  7. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  8. for (String beanName : beanNames) {
  9. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  10. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  11. if (isFactoryBean(beanName)) {
  12. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
  13. if (bean instanceof FactoryBean) {
  14. FactoryBean<?> factory = (FactoryBean<?>) bean;
  15. boolean isEagerInit;
  16. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  17. isEagerInit = AccessController.doPrivileged(
  18. (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
  19. getAccessControlContext());
  20. }
  21. else {
  22. isEagerInit = (factory instanceof SmartFactoryBean &&
  23. ((SmartFactoryBean<?>) factory).isEagerInit());
  24. }
  25. if (isEagerInit) {
  26. getBean(beanName);
  27. }
  28. }
  29. }
  30. else {
  31. getBean(beanName);
  32. }
  33. }
  34. // 代码略...
  35. }
  36. }
  37. }

3、AbstractBeanFactory

getBean方法是定义在其父类AbstractBeanFactory中

  1. public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
  2. @Override
  3. public Object getBean(String name) throws BeansException {
  4. return doGetBean(name, null, null, false);
  5. }
  6. protected <T> T doGetBean(
  7. String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  8. throws BeansException {
  9. String beanName = transformedBeanName(name);
  10. Object bean;
  11. // 3.1、检查缓存中或者实例工厂中是否有对应的实例
  12. // 在创建单例Bean时会存在依赖注入的情况,Spring会通过ObjectFactory如提早曝光Bean对象,避免循环依赖,
  13. Object sharedInstance = getSingleton(beanName);
  14. if (sharedInstance != null && args == null) {
  15. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  16. }else {
  17. // Fail if we're already creating this bean instance:
  18. // We're assumably within a circular reference.
  19. if (isPrototypeCurrentlyInCreation(beanName)) {
  20. throw new BeanCurrentlyInCreationException(beanName);
  21. }
  22. // Check if bean definition exists in this factory.
  23. BeanFactory parentBeanFactory = getParentBeanFactory();
  24. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  25. // Not found -> check parent.
  26. String nameToLookup = originalBeanName(name);
  27. if (parentBeanFactory instanceof AbstractBeanFactory) {
  28. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  29. nameToLookup, requiredType, args, typeCheckOnly);
  30. }
  31. else if (args != null) {
  32. // Delegation to parent with explicit args.
  33. return (T) parentBeanFactory.getBean(nameToLookup, args);
  34. }
  35. else if (requiredType != null) {
  36. // No args -> delegate to standard getBean method.
  37. return parentBeanFactory.getBean(nameToLookup, requiredType);
  38. }
  39. else {
  40. return (T) parentBeanFactory.getBean(nameToLookup);
  41. }
  42. }
  43. if (!typeCheckOnly) {
  44. markBeanAsCreated(beanName);
  45. }
  46. StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
  47. .tag("beanName", name);
  48. try {
  49. if (requiredType != null) {
  50. beanCreation.tag("beanType", requiredType::toString);
  51. }
  52. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  53. checkMergedBeanDefinition(mbd, beanName, args);
  54. // 3.2、检查是否存在依赖,若需要进行递归创建依赖
  55. String[] dependsOn = mbd.getDependsOn();
  56. if (dependsOn != null) {
  57. for (String dep : dependsOn) {
  58. if (isDependent(beanName, dep)) {
  59. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  60. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  61. }
  62. registerDependentBean(dep, beanName);
  63. try {
  64. getBean(dep);
  65. }
  66. catch (NoSuchBeanDefinitionException ex) {
  67. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  68. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  69. }
  70. }
  71. }
  72. // 3.3、通过回调的方式创建Bean
  73. if (mbd.isSingleton()) {
  74. sharedInstance = getSingleton(beanName, () -> {
  75. try {
  76. // 此处会调用AbstractAutowireCapableBeanFactory的doCreateBean方法进行Bean的实例化
  77. return createBean(beanName, mbd, args);
  78. }
  79. catch (BeansException ex) {
  80. // Explicitly remove instance from singleton cache: It might have been put there
  81. // eagerly by the creation process, to allow for circular reference resolution.
  82. // Also remove any beans that received a temporary reference to the bean.
  83. destroySingleton(beanName);
  84. throw ex;
  85. }
  86. });
  87. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  88. }
  89. else if (mbd.isPrototype()) {
  90. // It's a prototype -> create a new instance.
  91. Object prototypeInstance = null;
  92. try {
  93. beforePrototypeCreation(beanName);
  94. prototypeInstance = createBean(beanName, mbd, args);
  95. }
  96. finally {
  97. afterPrototypeCreation(beanName);
  98. }
  99. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  100. }
  101. else {
  102. String scopeName = mbd.getScope();
  103. if (!StringUtils.hasLength(scopeName)) {
  104. throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
  105. }
  106. Scope scope = this.scopes.get(scopeName);
  107. if (scope == null) {
  108. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  109. }
  110. try {
  111. Object scopedInstance = scope.get(beanName, () -> {
  112. beforePrototypeCreation(beanName);
  113. try {
  114. return createBean(beanName, mbd, args);
  115. }
  116. finally {
  117. afterPrototypeCreation(beanName);
  118. }
  119. });
  120. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  121. }
  122. catch (IllegalStateException ex) {
  123. throw new ScopeNotActiveException(beanName, scopeName, ex);
  124. }
  125. }
  126. }
  127. catch (BeansException ex) {
  128. beanCreation.tag("exception", ex.getClass().toString());
  129. beanCreation.tag("message", String.valueOf(ex.getMessage()));
  130. cleanupAfterBeanCreationFailure(beanName);
  131. throw ex;
  132. }
  133. finally {
  134. beanCreation.end();
  135. }
  136. }
  137. // 3.4、类型检查
  138. if (requiredType != null && !requiredType.isInstance(bean)) {
  139. try {
  140. T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
  141. if (convertedBean == null) {
  142. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  143. }
  144. return convertedBean;
  145. }
  146. catch (TypeMismatchException ex) {
  147. if (logger.isTraceEnabled()) {
  148. logger.trace("Failed to convert bean '" + name + "' to required type '" +
  149. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  150. }
  151. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  152. }
  153. }
  154. return (T) bean;
  155. }
  156. }

02|循环依赖对象创建分析

  1. //开始初始化Bean
  2. DefaultListableBeanFactory#preInstantiateSingletons
  3. AbstractBeanFactory#getBean
  4. AbstractBeanFactory#doGetBean
  5. // #从三级缓存中获取Bean,解决循环依赖关键位置,第一次返回null
  6. DefaultSingletonBeanRegistry#getSingleton
  7. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  8. // 从一级缓存获取,获取成功则对象已经创建成功
  9. Object singletonObject = this.singletonObjects.get(beanName);
  10. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  11. synchronized (this.singletonObjects) {
  12. // 从二级缓存取
  13. singletonObject = this.earlySingletonObjects.get(beanName);
  14. if (singletonObject == null && allowEarlyReference) {
  15. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  16. if (singletonFactory != null) {
  17. // 从三级缓存取,获取成功则从三件缓存**剪切**对象到二级缓存
  18. singletonObject = singletonFactory.getObject();
  19. this.earlySingletonObjects.put(beanName, singletonObject);
  20. this.singletonFactories.remove(beanName);
  21. }
  22. }
  23. }
  24. }
  25. return singletonObject;
  26. }
  27. // 创建实例bean,还未对实例bean对象属性进行赋值
  28. AbstractAutowireCapableBeanFactory#doCreateBean
  29. AbstractAutowireCapableBeanFactory#createBeanInstance
  30. // 将实例bean包装未ObjectFactory对象,放入三级缓存提前暴露对象 DefaultSingletonBeanRegistry#addSingletonFactory(ObjectFactory)
  31. // 属性填充
  32. AbstractAutowireCapableBeanFactory#populateBean
  33. AbstractAutowireCapableBeanFactory#autowire*
  34. AbstractBeanFactory#getBean
  35. AbstractBeanFactory#doGetBean
  36. // 继续尝试从三级缓存中获取对象,如获取失败,执行bean创建逻辑,并放入缓存供依赖对象获取填充
  37. DefaultSingletonBeanRegistry#getSingleton

image.png