AnnotationConfigApplicationContext容器初始化

AnnotationConfigApplicationContext容器初始化目录
(Spring源码分析)AnnotationConfigApplicationContext容器初始化 this() && register()
(Spring源码分析)AnnotationConfigApplicationContext容器初始化 refresh()#invokeBeanFactoryPostProcessors
(Spring源码分析)AnnotationConfigApplicationContext容器初始化 refresh()#registerBeanPostProcessors
(Spring源码分析)AnnotationConfigApplicationContext容器初始化 refresh()#finishBeanFactoryInitialization
 

使用AnnotationConfigApplicationContext容器

public static void main(String[] args) {
  AnnotationConfigApplicationContext applicationContext = new 
AnnotationConfigApplicationContext(AppConfig.class);
  TestService testService = applicationContext.getBean(TestService.class);
  System.out.println(testService.sout());
}

AppConfig配置类

@Configuration
@ComponentScan("com.leon.learning.build.applicationcontext")
public class AppConfig {
}

AnnotationConfigApplicationContext容器方法

AnnotationConfigApplicationContext applicationContext = new 
AnnotationConfigApplicationContext(AppConfig.class);

这段代码会调用AnnotationConfigApplicationContext类的无参构造方法
 

AnnotationConfigApplicationContext容器方法

AnnotationConfigApplicationContext applicationContext = new 
AnnotationConfigApplicationContext(AppConfig.class);

这段代码会调用AnnotationConfigApplicationContext类的无参构造方法

/**
 * 这个构造方法需要传入一个javaconfig注解了的配置类
 * 然后会把这个被注解了javaconfig的类通过注解读取器读取后继而解析
 */
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
  // 这里由于他有父类,故而会先调用父类的无参构造方法,然后才会调用自己的无参构造方法
  // 在自己构造方法中初始一个读取器和扫描器
  this();
	register(annotatedClasses); // 这里仅仅只是将annotatedClasses作为bean放入beanDefinitionMap中
	refresh(); // AnnotationConfigApplicationContext容器中最重要的方法,将annotatedClasses中
扫描的bean加入beanDefinitionMap中
}

1、this()

this()方法主要是初始化BeanFactory容器

AnnotationConfigApplicationContext父类GenericApplicationContext的无参构造方法中

/**
 * 初始化BeanFactory
 */
public GenericApplicationContext() {
  this.beanFactory = new DefaultListableBeanFactory();
}

然后执行AnnotationConfigApplicationContext自己的无参构造方法

/**
 * 初始化注解读取器和扫描器
 */
public AnnotationConfigApplicationContext() {
  this.reader = new AnnotatedBeanDefinitionReader(this);
  this.scanner = new ClassPathBeanDefinitionScanner(this);
}

2、register(annotatedClasses)

register(annotatedClasses)方法主要是将传入的配置类加入到BeanDefinitionMap中,但是配置类中配置
的包扫描路径下的bean并没有添加到BeanDefinitionMap中
/**
 * 判断annotatedClasses不为空,并调用AnnotatedBeanDefinitionReader注解读取器去读取配置类
annotatedClasses中的配置
 */
public void register(Class<?>... annotatedClasses) {
  Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
  this.reader.register(annotatedClasses); // 调用AnnotatedBeanDefinitionReader注解读取器去读
取配置类annotatedClasses中的配置
}

2.1、this.reader.register(annotatedClasses)

/**
 * 循环调用AnnotatedBeanDefinitionReader注解读取器去读取配置类
 */
public void register(Class<?>... annotatedClasses) {
  for (Class<?> annotatedClass : annotatedClasses) {
    registerBean(annotatedClass);
  }
}

2.1.1、registerBean(annotatedClass)

public void registerBean(Class<?> annotatedClass) {
  doRegisterBean(annotatedClass, null, null, null);
}

2.1.1.1、doRegisterBean(annotatedClass, null, null, null)

<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
                        @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

  // 这里的这个AnnotatedGenericBeanDefinition对象仅仅只是在new AnnotationConfigApplicationContext(传入的配置类)
  AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass); // 将Bean的配置信息转换成AnnotatedGenericBeanDefinition,它继承了BeanDefinition接口,包含bean的属性

  // @Conditional装配条件判断是否需要跳过注册
  if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
    return;
  }

  abd.setInstanceSupplier(instanceSupplier);
  ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); // 解析bean作用域,如果使有@Scope注解指定了bean的作用域将设置成指定的作用域,否则默认为singleton(单例)
  abd.setScope(scopeMetadata.getScopeName()); // 为AnnotatedGenericBeanDefinition对象设置scope(作用域)属性
  String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); // 生成beanName
  AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); // 解析AnnotatedGenericBeanDefinition对象中lazy、Primary、DependsOn、Role、Description属性

  if (qualifiers != null) { // @Qualifier特殊限定符处理
    for (Class<? extends Annotation> qualifier : qualifiers) {
      if (Primary.class == qualifier) {
        abd.setPrimary(true);
      }
      else if (Lazy.class == qualifier) {
        abd.setLazyInit(true);
      }
      else {
        abd.addQualifier(new AutowireCandidateQualifier(qualifier));
      }
    }
  }

  // 处理applicationcontext容器加载完成后手动registerBean
  for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
    customizer.customize(abd);
  }

  BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); // 将beanName和AnnotatedGenericBeanDefinition封装在BeanDefinitionHolder中
  definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 创建代理对象
  BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); // 将BeanDefinition注册到BeanDefinitionMap中
}

2.1.1.1.1、BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry)

public static void registerBeanDefinition(
  BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
  throws BeanDefinitionStoreException {

  // Register bean definition under primary name.
  String beanName = definitionHolder.getBeanName();
  registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // 调用BeanDefinitionRegistry方法对BeanDefinition注册到ConCurrentHashMap中

  // Register aliases for bean name, if any.
  String[] aliases = definitionHolder.getAliases();
  if (aliases != null) {
    for (String alias : aliases) {
      registry.registerAlias(beanName, alias); // 注册别名
    }
  }
}

2.1.1.1.1.1、registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition())

/**
 * 对BeanDefinition注册到ConCurrentHashMap中
 */
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
  throws BeanDefinitionStoreException {
  // 校验beanName和beanDefinition不能为空
  Assert.hasText(beanName, "Bean name must not be empty");
  Assert.notNull(beanDefinition, "BeanDefinition must not be null");

  // beanDefinition校验
  if (beanDefinition instanceof AbstractBeanDefinition) {
    try {
      ((AbstractBeanDefinition) beanDefinition).validate();
    }
    catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                                             "Validation of bean definition failed", ex);
    }
  }

  BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); // 判断beanDefinitionMap中是否含有相同beanName的BeanDefinition

  // 如果beanDefinitionMap中存在相同beanName的BeanDefinition
  if (existingDefinition != null) {
    // 判断是否允许含有同样的beanName对BeanDefinition进行覆盖
    if (!isAllowBeanDefinitionOverriding()) {
      throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                                             "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
                                             "': There is already [" + existingDefinition + "] bound.");
    }
    // 参数校验
    else if (existingDefinition.getRole() < beanDefinition.getRole()) {
      // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
      if (logger.isWarnEnabled()) {
        logger.warn("Overriding user-defined bean definition for bean '" + beanName +
                    "' with a framework-generated bean definition: replacing [" +
                    existingDefinition + "] with [" + beanDefinition + "]");
      }
    }
    else if (!beanDefinition.equals(existingDefinition)) {
      if (logger.isInfoEnabled()) {
        logger.info("Overriding bean definition for bean '" + beanName +
                    "' with a different definition: replacing [" + existingDefinition +
                    "] with [" + beanDefinition + "]");
      }
    }
    else {
      if (logger.isDebugEnabled()) {
        logger.debug("Overriding bean definition for bean '" + beanName +
                     "' with an equivalent definition: replacing [" + existingDefinition +
                     "] with [" + beanDefinition + "]");
      }
    }
    this.beanDefinitionMap.put(beanName, beanDefinition); // 将beanName和beanDefinition存到beanDefinitionMap中
  }

  // 如果beanDefinitionMap中不存在相同beanName的BeanDefinition
  else {
    if (hasBeanCreationStarted()) {
      // Cannot modify startup-time collection elements anymore (for stable iteration)
      synchronized (this.beanDefinitionMap) { // 同步代码块
        this.beanDefinitionMap.put(beanName, beanDefinition); // 将beanName和beanDefinition存到beanDefinitionMap中
        List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
        updatedDefinitions.addAll(this.beanDefinitionNames);
        updatedDefinitions.add(beanName);
        this.beanDefinitionNames = updatedDefinitions;
        if (this.manualSingletonNames.contains(beanName)) {
          Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
          updatedSingletons.remove(beanName);
          this.manualSingletonNames = updatedSingletons;
        }
      }
    }
    else {
      // Still in startup registration phase
      this.beanDefinitionMap.put(beanName, beanDefinition);
      this.beanDefinitionNames.add(beanName);
      this.manualSingletonNames.remove(beanName);
    }
    this.frozenBeanDefinitionNames = null;
  }

  if (existingDefinition != null || containsSingleton(beanName)) {
    resetBeanDefinition(beanName);
  }
}

refresh()

在refresh()中,主要有12个方法,下面主要对invokeBeanFactoryPostProcessors(beanFactory)、
registerBeanPostProcessors(beanFactory)、finishBeanFactoryInitialization(beanFactory)方法进
行分析
@Override
public void refresh() throws BeansException, IllegalStateException {
  synchronized (this.startupShutdownMonitor) {
    // 准备工作包括设置启动时间,是否激活标识位
    // 1.刷新预处理的前期准备
    prepareRefresh();

    // 2.获取内部的Bean工厂
    ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

    // 3.准备需要刷新后的工厂,为beanFactory属性设置初始值
    prepareBeanFactory(beanFactory);

    try {
      // 4.这个方法在当前版本的Spring是没用,留着给扩展使用
      postProcessBeanFactory(beanFactory);

      // 5.在Spring的环境中去执行已经被注册的factory processors
      // 设置执行自定的ProcessBeanFactory和Spring内部自己定义的
      // 把类给扫描出来、处理@Import、@ImportSource导入资源文件,处理MapperScan
      // scan -- put beanDefinitionMap
      invokeBeanFactoryPostProcessors(beanFactory);

      // 6.注册beanPostProcessor
      registerBeanPostProcessors(beanFactory);

      // 7.初始化MessageSource
      initMessageSource();

      // 8.初始化应用实践广播器
      initApplicationEventMulticaster();

      // 9.这个方法在当前版本的Spring是没用,留着给扩展使用
      onRefresh();

      // 10.Check for listener beans and register them.
      registerListeners();

      // 11.new对象,单例,将beanFactory中的beanDefinitionMap中的bean进行初始化,然后放到单例池singletonObjects中
      finishBeanFactoryInitialization(beanFactory);

      // 12.Last step: publish corresponding event.
      finishRefresh();
    }

    catch (BeansException ex) {
      if (logger.isWarnEnabled()) {
        logger.warn("Exception encountered during context initialization - " +
                    "cancelling refresh attempt: " + ex);
      }

      // Destroy already created singletons to avoid dangling resources.
      destroyBeans();

      // Reset 'active' flag.
      cancelRefresh(ex);

      // Propagate exception to caller.
      throw ex;
    }

    finally {
      // Reset common introspection caches in Spring's core, since we
      // might not ever need metadata for singleton beans anymore...
      resetCommonCaches();
    }
  }
}

invokeBeanFactoryPostProcessors(beanFactory)

invokeBeanFactoryPostProcessors(beanFactory)主要是作用如下:

在Spring的环境中去执行已经被注册的BeanFactoryPostProcessors
设置执行Spring内部自己定义的BeanFactoryPostProcessors
将配置类中的bean扫描出来,添加到BeanDefinitionMap中
处理@Import、@ImportSource导入资源文件
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  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(beanFactory, beanFactoryPostProcessors)

public static void invokeBeanFactoryPostProcessors(
  ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

  // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  Set<String> processedBeans = new HashSet<>();

  if (beanFactory instanceof BeanDefinitionRegistry) {
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); // 用来存放实现BeanFactoryPostProcessor接口的类
    List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); // 用来存放实现BeanDefinitionRegistryPostProcessor接口的类

    // 遍历beanFactoryPostProcessors,如果是实现BeanDefinitionRegistryPostProcessor的,直接执行实现类中实现的postProcessBeanDefinitionRegistry方法
    for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
      if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
        BeanDefinitionRegistryPostProcessor registryProcessor =
          (BeanDefinitionRegistryPostProcessor) postProcessor;
        registryProcessor.postProcessBeanDefinitionRegistry(registry);
        registryProcessors.add(registryProcessor);
      }
      else {
        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.
    List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // 用来存放beanDefinitionMap中继承了BeanDefinitionRegistryPostProcessor接口的bean

    // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
    // 查找beanDefinitionMap中继承了BeanDefinitionRegistryPostProcessor接口的bean
    String[] postProcessorNames =
      beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    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); // 将beanDefinitionMap中继承了BeanDefinitionRegistryPostProcessor接口的bean添加到registryProcessors以便后面执行postProcessBeanFactory方法
    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    currentRegistryProcessors.clear();

    // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
    postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    for (String ppName : postProcessorNames) {
      if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
        processedBeans.add(ppName);
      }
    }
    sortPostProcessors(currentRegistryProcessors, beanFactory);
    registryProcessors.addAll(currentRegistryProcessors);
    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    currentRegistryProcessors.clear();

    // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
    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);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();
    }

    // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
    // 执行实现了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口实现的postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  }

  else {
    // Invoke factory processors registered with the context instance.
    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!
  String[] postProcessorNames =
    beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

  // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  // Ordered, and the rest.
  List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  List<String> orderedPostProcessorNames = new ArrayList<>();
  List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  for (String ppName : postProcessorNames) {
    if (processedBeans.contains(ppName)) {
      // skip - already processed in first phase above
    }
    else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
      priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    }
    else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
      orderedPostProcessorNames.add(ppName);
    }
    else {
      nonOrderedPostProcessorNames.add(ppName);
    }
  }

  // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

  // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
  for (String postProcessorName : orderedPostProcessorNames) {
    orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  }
  sortPostProcessors(orderedPostProcessors, beanFactory);
  invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

  // Finally, invoke all other BeanFactoryPostProcessors.
  List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
  for (String postProcessorName : nonOrderedPostProcessorNames) {
    nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  }
  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();
}

invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry)

private static void invokeBeanDefinitionRegistryPostProcessors(
  Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
  // 执行postProcessors中实现了BeanFactoryPostProcessor接口中的postProcessBeanDefinitionRegistry方法
  for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
    postProcessor.postProcessBeanDefinitionRegistry(registry);
  }
}

postProcessor.postProcessBeanDefinitionRegistry(registry)

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  int registryId = System.identityHashCode(registry); // 获取registryId
  if (this.registriesPostProcessed.contains(registryId)) {
    throw new IllegalStateException(
      "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
  }
  if (this.factoriesPostProcessed.contains(registryId)) {
    throw new IllegalStateException(
      "postProcessBeanFactory already called on this post-processor against " + registry);
  }
  this.registriesPostProcessed.add(registryId);

  processConfigBeanDefinitions(registry);
}

processConfigBeanDefinitions(registry)

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
  List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
  String[] candidateNames = registry.getBeanDefinitionNames(); // 取出beanDefinition的className数组

  // 遍历beanDefinition的className数组
  for (String beanName : candidateNames) {
    BeanDefinition beanDef = registry.getBeanDefinition(beanName); // 取出BeanDefinition
    if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
        ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
      if (logger.isDebugEnabled()) {
        logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
      }
    }
    else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { // 检查该BeanDefinition对象是否被@Configuration注解标识
      configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
    }
  }

  // Return immediately if no @Configuration classes were found
  if (configCandidates.isEmpty()) {
    return;
  }

  // Sort by previously determined @Order value, if applicable
  configCandidates.sort((bd1, bd2) -> {
    int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
    int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
    return Integer.compare(i1, i2);
  });

  // Detect any custom bean name generation strategy supplied through the enclosing application context
  SingletonBeanRegistry sbr = null;
  if (registry instanceof SingletonBeanRegistry) {
    sbr = (SingletonBeanRegistry) registry;
    if (!this.localBeanNameGeneratorSet) {
      BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
      if (generator != null) {
        this.componentScanBeanNameGenerator = generator;
        this.importBeanNameGenerator = generator;
      }
    }
  }

  if (this.environment == null) {
    this.environment = new StandardEnvironment();
  }

  // Parse each @Configuration class
  ConfigurationClassParser parser = new ConfigurationClassParser(
    this.metadataReaderFactory, this.problemReporter, this.environment,
    this.resourceLoader, this.componentScanBeanNameGenerator, registry); // 创建Configuration配置解析器

  Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
  Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
  do {
    parser.parse(candidates); // 解析带有@Configuration标识的配置bean
    parser.validate();

    Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
    configClasses.removeAll(alreadyParsed);

    // Read the model and create bean definitions based on its content
    if (this.reader == null) {
      this.reader = new ConfigurationClassBeanDefinitionReader(
        registry, this.sourceExtractor, this.resourceLoader, this.environment,
        this.importBeanNameGenerator, parser.getImportRegistry());
    }
    this.reader.loadBeanDefinitions(configClasses);
    alreadyParsed.addAll(configClasses);

    candidates.clear();
    if (registry.getBeanDefinitionCount() > candidateNames.length) {
      String[] newCandidateNames = registry.getBeanDefinitionNames();
      Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
      Set<String> alreadyParsedClasses = new HashSet<>();
      for (ConfigurationClass configurationClass : alreadyParsed) {
        alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
      }
      for (String candidateName : newCandidateNames) {
        if (!oldCandidateNames.contains(candidateName)) {
          BeanDefinition bd = registry.getBeanDefinition(candidateName);
          if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
              !alreadyParsedClasses.contains(bd.getBeanClassName())) {
            candidates.add(new BeanDefinitionHolder(bd, candidateName));
          }
        }
      }
      candidateNames = newCandidateNames;
    }
  }
  while (!candidates.isEmpty());

  // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
  if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
    sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
  }

  if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
    // Clear cache in externally provided MetadataReaderFactory; this is a no-op
    // for a shared cache since it'll be cleared by the ApplicationContext.
    ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
  }
}

parser.parse(candidates)

public void parse(Set<BeanDefinitionHolder> configCandidates) {
  this.deferredImportSelectors = new LinkedList<>();

  for (BeanDefinitionHolder holder : configCandidates) {
    BeanDefinition bd = holder.getBeanDefinition();
    try {
      if (bd instanceof AnnotatedBeanDefinition) { // 该BeanDefinition的实现类是AnnotatedBeanDefinition
        parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName()); // getMetadata()是获取该AnnotatedBeanDefinition对象中的所有的注解
      }
      else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
        parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
      }
      else {
        parse(bd.getBeanClassName(), holder.getBeanName());
      }
    }
    catch (BeanDefinitionStoreException ex) {
      throw ex;
    }
    catch (Throwable ex) {
      throw new BeanDefinitionStoreException(
        "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
    }
  }

  processDeferredImportSelectors();
}

processConfigurationClass(new ConfigurationClass(metadata, beanName))

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
  if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
    return;
  }

  ConfigurationClass existingClass = this.configurationClasses.get(configClass);
  if (existingClass != null) {
    if (configClass.isImported()) {
      if (existingClass.isImported()) {
        existingClass.mergeImportedBy(configClass);
      }
      // Otherwise ignore new imported config class; existing non-imported class overrides it.
      return;
    }
    else {
      // Explicit bean definition found, probably replacing an import.
      // Let's remove the old one and go with the new one.
      this.configurationClasses.remove(configClass);
      this.knownSuperclasses.values().removeIf(configClass::equals);
    }
  }

  // Recursively process the configuration class and its superclass hierarchy.
  // 递归处理配置类和它的父类
  SourceClass sourceClass = asSourceClass(configClass);
  do {
    sourceClass = doProcessConfigurationClass(configClass, sourceClass);
  }
  while (sourceClass != null);

  this.configurationClasses.put(configClass, configClass);
}

doProcessConfigurationClass(configClass, sourceClass)

@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
  throws IOException {

  // Recursively process any member (nested) classes first
  processMemberClasses(configClass, sourceClass);

  // Process any @PropertySource annotations
  // 判断sourceClass的注解中是否有@PropertySource注解
  for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
    sourceClass.getMetadata(), PropertySources.class,
    org.springframework.context.annotation.PropertySource.class)) {
    if (this.environment instanceof ConfigurableEnvironment) {
      processPropertySource(propertySource);
    }
    else {
      logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
                  "]. Reason: Environment must implement ConfigurableEnvironment");
    }
  }

  // Process any @ComponentScan annotations
  // 判断sourceClass的注解中是否有@ComponentScan注解
  Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
    sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  if (!componentScans.isEmpty() &&
      !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { // @ComponentScan注解可以在同一个配置类中使用多次
    for (AnnotationAttributes componentScan : componentScans) {
      // The config class is annotated with @ComponentScan -> perform the scan immediately
      Set<BeanDefinitionHolder> scannedBeanDefinitions =
        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // 使用ComponentScanAnnotationParser解析器去扫描并注册该bean
      // Check the set of scanned definitions for any further config classes and parse recursively if needed
      for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
        BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
        if (bdCand == null) {
          bdCand = holder.getBeanDefinition();
        }
        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
          parse(bdCand.getBeanClassName(), holder.getBeanName());
        }
      }
    }
  }

  // Process any @Import annotations
  processImports(configClass, sourceClass, getImports(sourceClass), true);

  // Process any @ImportResource annotations
  AnnotationAttributes importResource =
    AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
  if (importResource != null) {
    String[] resources = importResource.getStringArray("locations");
    Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
    for (String resource : resources) {
      String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
      configClass.addImportedResource(resolvedResource, readerClass);
    }
  }

  // Process individual @Bean methods
  Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
  for (MethodMetadata methodMetadata : beanMethods) {
    configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
  }

  // Process default methods on interfaces
  processInterfaces(configClass, sourceClass);

  // Process superclass, if any
  if (sourceClass.getMetadata().hasSuperClass()) {
    String superclass = sourceClass.getMetadata().getSuperClassName();
    if (superclass != null && !superclass.startsWith("java") &&
        !this.knownSuperclasses.containsKey(superclass)) {
      this.knownSuperclasses.put(superclass, configClass);
      // Superclass found, return its annotation metadata and recurse
      return sourceClass.getSuperClass();
    }
  }

  // No superclass -> processing is complete
  return null;
}

this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName())

/**
 * 得到basePackages
 */
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
  ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
                                                                              componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

  Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
  boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
  scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
                               BeanUtils.instantiateClass(generatorClass));

  ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
  if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
    scanner.setScopedProxyMode(scopedProxyMode);
  }
  else {
    Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
    scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
  }

  scanner.setResourcePattern(componentScan.getString("resourcePattern"));

  for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
    for (TypeFilter typeFilter : typeFiltersFor(filter)) {
      scanner.addIncludeFilter(typeFilter);
    }
  }
  for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
    for (TypeFilter typeFilter : typeFiltersFor(filter)) {
      scanner.addExcludeFilter(typeFilter);
    }
  }

  boolean lazyInit = componentScan.getBoolean("lazyInit");
  if (lazyInit) {
    scanner.getBeanDefinitionDefaults().setLazyInit(true);
  }

  Set<String> basePackages = new LinkedHashSet<>();
  String[] basePackagesArray = componentScan.getStringArray("basePackages");
  for (String pkg : basePackagesArray) {
    String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
                                                           ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    Collections.addAll(basePackages, tokenized);
  }
  for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
    basePackages.add(ClassUtils.getPackageName(clazz));
  }
  if (basePackages.isEmpty()) {
    basePackages.add(ClassUtils.getPackageName(declaringClass));
  }

  scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
    @Override
    protected boolean matchClassName(String className) {
      return declaringClass.equals(className);
    }
  });
  return scanner.doScan(StringUtils.toStringArray(basePackages)); // 扫描指定路径下的bean
}

scanner.doScan(StringUtils.toStringArray(basePackages))

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
  Assert.notEmpty(basePackages, "At least one base package must be specified");
  Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();

  // 循环basePackage
  for (String basePackage : basePackages) {
    Set<BeanDefinition> candidates = findCandidateComponents(basePackage); // 扫描basePackage路径下所有的bean,返回BeanDefinition对象Set集合
    for (BeanDefinition candidate : candidates) {
      ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
      candidate.setScope(scopeMetadata.getScopeName());
      String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
      if (candidate instanceof AbstractBeanDefinition) {
        postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
      }
      if (candidate instanceof AnnotatedBeanDefinition) {
        AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
      }
      if (checkCandidate(beanName, candidate)) {
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
        definitionHolder =
          AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
        beanDefinitions.add(definitionHolder);
        registerBeanDefinition(definitionHolder, this.registry); // 注册bean到beanDefinitionMap中
      }
    }
  }
  return beanDefinitions;
}

registerBeanDefinition(definitionHolder, this.registry)

看到BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry)这个方法调
用,其实就是在上一节已经讲过了,就是将bean注册到BeanDefinitionMap中
protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
  BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}

registerBeanPostProcessors(beanFactory)

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

 

PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this)

public static void registerBeanPostProcessors(
  ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
  // 查询beanDefinitionMap中所有实现了BeanPostProcessor接口的类名称数组
  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.
  // 将beanFactory作为BeanPostProcessors作为后置处理器添加到的beanPostProcessors中
  int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
  beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

  // Separate between BeanPostProcessors that implement PriorityOrdered,
  // Ordered, and the rest.
  // 对实现了不同接口的后置处理器进行分类
  List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
  List<String> orderedPostProcessorNames = new ArrayList<>();
  List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  for (String ppName : postProcessorNames) {
    if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      priorityOrderedPostProcessors.add(pp);
      if (pp instanceof MergedBeanDefinitionPostProcessor) {
        internalPostProcessors.add(pp);
      }
    }
    else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
      orderedPostProcessorNames.add(ppName);
    }
    else {
      nonOrderedPostProcessorNames.add(ppName);
    }
  }

  // 注册实现了PriorityOrdered接口的处理器
  // First, register the BeanPostProcessors that implement PriorityOrdered.
  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

  // Next, register the BeanPostProcessors that implement Ordered.
  // 注册实现了Ordered接口的处理器
  List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
  for (String ppName : orderedPostProcessorNames) {
    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    orderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {
      internalPostProcessors.add(pp);
    }
  }
  sortPostProcessors(orderedPostProcessors, beanFactory);
  registerBeanPostProcessors(beanFactory, orderedPostProcessors);

  // Now, register all regular BeanPostProcessors.
  // 注册既没有实现PriorityOrdered接口的也没有实现Ordered接口的处理器
  List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
  for (String ppName : nonOrderedPostProcessorNames) {
    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    nonOrderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {
      internalPostProcessors.add(pp);
    }
  }
  registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

  // Finally, re-register all internal BeanPostProcessors.
  // 最后,重新注册所有的后置处理器
  sortPostProcessors(internalPostProcessors, beanFactory);
  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).
  beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors)

private static void registerBeanPostProcessors(
  ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
  for (BeanPostProcessor postProcessor : postProcessors) {
    beanFactory.addBeanPostProcessor(postProcessor);
  }
}

beanFactory.addBeanPostProcessor(postProcessor)

@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
  Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
  // Remove from old position, if any
  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;
  }
  // Add to end of list
  this.beanPostProcessors.add(beanPostProcessor);
}

finishBeanFactoryInitialization(beanFactory)

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

	// Register a default embedded value resolver if no bean post-processor
	// (such as a PropertyPlaceholderConfigurer bean) registered any before:
	// at this point, primarily for resolution in annotation attribute values.
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	// 初始化非懒加载的bean
	beanFactory.preInstantiateSingletons();
}

beanFactory.preInstantiateSingletons()

@Override
public void preInstantiateSingletons() throws BeansException {
  if (logger.isDebugEnabled()) {
    logger.debug("Pre-instantiating singletons in " + this);
  }

  // 所有bean的beanName
  // 可能需要实例化的class(lazy、scope):懒加载的不实例化,非单例的不实例化
  List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

  // 触发所有非延迟加载单例beans的初始化,主要步骤为调用getBean()方法来对bean进行初始化
  for (String beanName : beanNames) {
    RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 当BeanDefinition是抽象的,并且不是单例的,并且是懒加载的就不实例化bean
      if (isFactoryBean(beanName)) { // 当该bean继承了FactoryBean时
        Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
        if (bean instanceof FactoryBean) {
          final FactoryBean<?> factory = (FactoryBean<?>) bean;
          boolean isEagerInit;
          if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                                        ((SmartFactoryBean<?>) factory)::isEagerInit,
                                                        getAccessControlContext());
          }
          else {
            isEagerInit = (factory instanceof SmartFactoryBean &&
                           ((SmartFactoryBean<?>) factory).isEagerInit());
          }
          if (isEagerInit) {
            getBean(beanName);
          }
        }
      }
      else {
        getBean(beanName); // 初始化该bean
      }
    }
  }

  // Trigger post-initialization callback for all applicable beans...
  for (String beanName : beanNames) {
    Object singletonInstance = getSingleton(beanName);
    if (singletonInstance instanceof SmartInitializingSingleton) {
      final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
      if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
          smartSingleton.afterSingletonsInstantiated();
          return null;
        }, getAccessControlContext());
      }
      else {
        smartSingleton.afterSingletonsInstantiated();
      }
    }
  }
}

getBean(beanName)

@Override
public Object getBean(String name) throws BeansException {
  return doGetBean(name, null, null, false);
}

doGetBean(name, null, null, false)

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
                          @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

  // 这里不直接name主要是因为alias和FactoryBean的原因
  // 1、别名需要转换成真正的beanName
  // 2、如果传入的name是实现了FactoryBean接口的话,那么传入的name是以&开头的,需要将首字母&移除
  final String beanName = transformedBeanName(name); // 获取beanName
  Object bean;

  // 这个方法在初始化的时候会调用,在getBean的时候也会调用,原因:
  //
  // 尝试从三级缓存中获取bean实例
  //
  // Spring循环依赖的原理:
  // 在创建单例bean的时候会存在依赖注入的情况,为了避免循环依赖,Spring在创建bean的原则是不等bean创建完成就会将创建bean的ObjectFactory提早曝光,添加到singletonFactories中
  // 将ObjectFactory加入到缓存中,一旦下一个bean创建的时候需要依赖注入上个bean则直接从缓存中获取ObjectFactory
  Object sharedInstance = getSingleton(beanName); // 根据beanName尝试从三级缓存中获取bean实例

  // 当三级缓存中存在此bean,表示当前该bean已创建完成 || 正在创建
  if (sharedInstance != null && args == null) {
    if (logger.isDebugEnabled()) {
      // 该bean在singletonFactories,但是还未初始化,因为此bean存在循环依赖
      if (isSingletonCurrentlyInCreation(beanName)) {
        logger.debug("Returning eagerly caFFched instance of singleton bean '" + beanName +
                     "' that is not fully initialized yet - a consequence of a circular reference");
      }
      else {
        logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
      }
    }
    // 返回对应的实例,有时候存在诸如BeanFactory的情况并不是直接返回实例本身而是返回指定方法返回的实例
    // 如果sharedInstance是普通的单例bean,下面的方法会直接返回,但如果sharedInstance是FactoryBean类型的,
    // 则需要调用getObject工厂方法获取bean实例,如果用户想获取FactoryBean本身,这里也不会做特别的处理
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  }

  // 当bean还未创建
  else {
    // Fail if we're already creating this bean instance:
    // We're assumably within a circular reference.
    // 如果该bean的scope是原型(phototype)不应该在初始化的时候创建
    if (isPrototypeCurrentlyInCreation(beanName)) {
      throw new BeanCurrentlyInCreationException(beanName);
    }

    // Check if bean definition exists in this factory.
    // 检查当前容器是否有父容器
    BeanFactory parentBeanFactory = getParentBeanFactory();

    // 如果父容器中存在此bean的实例,直接从父容器中获取bean的实例并返回
    // 父子容器:Spring和SpringMVC都是一个容器,Spring容器是父容器,SpringMVC是子容器
    // controller的bean放在SpringMVC的子容器中,service、mapper放在Spring父容器中
    // 子容器可以访问父容器中的bean实例,父容器不可以访问子容器中的实例
    // controller中可以注入service的依赖,但是service不能注入controller的依赖
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
      // Not found -> check parent.
      String nameToLookup = originalBeanName(name);
      if (parentBeanFactory instanceof AbstractBeanFactory) {
        return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
          nameToLookup, requiredType, args, typeCheckOnly);
      }
      else if (args != null) {
        // Delegation to parent with explicit args.
        return (T) parentBeanFactory.getBean(nameToLookup, args);
      }
      else {
        // No args -> delegate to standard getBean method.
        return parentBeanFactory.getBean(nameToLookup, requiredType);
      }
    }

    if (!typeCheckOnly) {
      // 添加到alreadyCreated set集合当中,表示他已经创建过了
      markBeanAsCreated(beanName);
    }

    try {
      // 从父容器中的BeanDefinitionMap和子容器中的BeanDefinitionMap合并的BeanDefinitionMap中获取BeanDefinition对象
      final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
      checkMergedBeanDefinition(mbd, beanName, args);

      // Guarantee initialization of beans that the current bean depends on.
      // 获取当前bean依赖注入的的属性,bean的初始化之前里面依赖的属性必须先初始化
      String[] dependsOn = mbd.getDependsOn();
      if (dependsOn != null) {
        for (String dep : dependsOn) {
          if (isDependent(beanName, dep)) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                            "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
          }
          registerDependentBean(dep, beanName);
          try {
            getBean(dep);
          }
          catch (NoSuchBeanDefinitionException ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                            "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
          }
        }
      }

      // Create bean instance.
      // 正式开始创建bean实例
      if (mbd.isSingleton()) { // 当该bean的scope为singleton或者为空时
        sharedInstance = getSingleton(beanName, () -> { // 从三级缓存中获取bean实例
          try {
            return createBean(beanName, mbd, args); // 真正创建bean
          }
          catch (BeansException ex) {
            // Explicitly remove instance from singleton cache: It might have been put there
            // eagerly by the creation process, to allow for circular reference resolution.
            // Also remove any beans that received a temporary reference to the bean.
            destroySingleton(beanName);
            throw ex;
          }
        });
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
      }

      // 创建 prototype 类型的 bean 实例
      else if (mbd.isPrototype()) {
        // It's a prototype -> create a new instance.
        Object prototypeInstance = null;
        try {
          beforePrototypeCreation(beanName);
          prototypeInstance = createBean(beanName, mbd, args);
        }
        finally {
          afterPrototypeCreation(beanName);
        }
        bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
      }

      // 创建其他类型的bean实例
      else {
        String scopeName = mbd.getScope();
        final Scope scope = this.scopes.get(scopeName);
        if (scope == null) {
          throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
        }
        try {
          Object scopedInstance = scope.get(beanName, () -> {
            beforePrototypeCreation(beanName);
            try {
              return createBean(beanName, mbd, args);
            }
            finally {
              afterPrototypeCreation(beanName);
            }
          });
          bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
        }
        catch (IllegalStateException ex) {
          throw new BeanCreationException(beanName,
                                          "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                          "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                          ex);
        }
      }
    }
    catch (BeansException ex) {
      cleanupAfterBeanCreationFailure(beanName);
      throw ex;
    }
  }

  // Check if required type matches the type of the actual bean instance.
  // 类型转换
  if (requiredType != null && !requiredType.isInstance(bean)) {
    try {
      T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
      if (convertedBean == null) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
      return convertedBean;
    }
    catch (TypeMismatchException ex) {
      if (logger.isDebugEnabled()) {
        logger.debug("Failed to convert bean '" + name + "' to required type '" +
                     ClassUtils.getQualifiedName(requiredType) + "'", ex);
      }
      throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
  }
  return (T) bean;
}

getSingleton(beanName)

@Override
@Nullable
public Object getSingleton(String beanName) {
  return getSingleton(beanName, true);
}

getSingleton(beanName, true)

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) { // allowEarlyReference表示是否允许从singletonFactories中通过getObject拿到对象
  // 尝试从三级缓存中获取bean实例
  Object singletonObject = this.singletonObjects.get(beanName); // 从一级缓存中获取bean

  // 如果一级缓存中不存在该bean实例  && 该bean正在创建中
  if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { // isSingletonCurrentlyInCreation(beanName)判断这个bean是否在创建过程中,对象是否有循环依赖
    synchronized (this.singletonObjects) {
      singletonObject = this.earlySingletonObjects.get(beanName); // 尝试从二级缓存中获取bean实例

      // 如果二级缓存中不存在giantbean实例 && 允许从singletonFactories从获取bean实例
      if (singletonObject == null && allowEarlyReference) {
        ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); // 从三级缓存中获取bean实例

        // 如果bean存在,将该bean实例从三级缓存升级到二级缓存中,并且从三级缓存中删除
        if (singletonFactory != null) {
          singletonObject = singletonFactory.getObject();
          this.earlySingletonObjects.put(beanName, singletonObject);
          this.singletonFactories.remove(beanName);
        }
      }
    }
  }
  return singletonObject;
}

createBean(beanName, mbd, args)

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  throws BeanCreationException {

  if (logger.isDebugEnabled()) {
    logger.debug("Creating instance of bean '" + beanName + "'");
  }
  RootBeanDefinition mbdToUse = mbd;

  // Make sure bean class is actually resolved at this point, and
  // clone the bean definition in case of a dynamically resolved Class
  // which cannot be stored in the shared merged bean definition.
  // 确认bean真实加载进行来了
  Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
    mbdToUse = new RootBeanDefinition(mbd);
    mbdToUse.setBeanClass(resolvedClass);
  }

  // Prepare method overrides.
  try {
    mbdToUse.prepareMethodOverrides();
  }
  catch (BeanDefinitionValidationException ex) {
    throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                                           beanName, "Validation of method overrides failed", ex);
  }

  try {
    // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    // 主要是来执行实现了InstantiationAwareBeanPostProcessor接口的BeanPostProcesser,但是返回的bean始终为null
    // AOP核心方法,用来处理使用@Aspect注解标识的bean,以便后面生成动态代理
    Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

    // 生成的bean实例存在就返回
    if (bean != null) {
      return bean;
    }
  }
  catch (Throwable ex) {
    throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                                    "BeanPostProcessor before instantiation of bean failed", ex);
  }

  try {
    // 实例化bean
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
  }
  catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
    // A previously detected exception with proper bean creation context already,
    // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
    throw ex;
  }
  catch (Throwable ex) {
    throw new BeanCreationException(
      mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  }
}

resolveBeforeInstantiation(beanName, mbdToUse)

@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
  Object bean = null;
  // 检测是否被解析过
  if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
    // Make sure bean class is actually resolved at this point.

    // hasInstantiationAwareBeanPostProcessors()是来判断容器中是否有InstantiationAwareBeanPostProcessor的实现bean
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      Class<?> targetType = determineTargetType(beanName, mbd); // 获取bean的目标类型
      if (targetType != null) {
        // 执行实现了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的前置处理方法postProcessBeforeInstantiation方法
        bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
        if (bean != null) {
          // 执行实现了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的后置处理方法postProcessAfterInitialization方法
          bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        }
      }
    }
    mbd.beforeInstantiationResolved = (bean != null);
  }
  return bean;
}

applyBeanPostProcessorsBeforeInstantiation(targetType, beanName)

@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
  for (BeanPostProcessor bp : getBeanPostProcessors()) {
    if (bp instanceof InstantiationAwareBeanPostProcessor) {
      InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
      if (result != null) {
        return result;
      }
    }
  }
  return null;
}

applyBeanPostProcessorsAfterInitialization(bean, beanName)

@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  throws BeansException {

  Object result = existingBean;
  for (BeanPostProcessor processor : getBeanPostProcessors()) {
    Object current = processor.postProcessAfterInitialization(result, beanName);
    if (current == null) {
      return result;
    }
    result = current;
  }
  return result;
}

doCreateBean(beanName, mbdToUse, args)

/**
 * 初始化bean实例(解决循环依赖问题)
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  throws BeanCreationException {

  // Instantiate the bean.
  BeanWrapper instanceWrapper = null;
  if (mbd.isSingleton()) {
	// 调用bean的构造方法进行初始化,经过这一步,bean属性并没有被赋值,只是一个空壳,这是bean初始化的【早期对象】
    instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  }

  // 创建bean实例转化成BeanWrapper对象
  if (instanceWrapper == null) {
    instanceWrapper = createBeanInstance(beanName, mbd, args);
  }
  final Object bean = instanceWrapper.getWrappedInstance();
  Class<?> beanType = instanceWrapper.getWrappedClass();
  if (beanType != NullBean.class) {
    mbd.resolvedTargetType = beanType;
  }

  // Allow post-processors to modify the merged bean definition.
  synchronized (mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
      try {
        // 处理bean中实现了MergedBeanDefinitionPostProcessor后置处理器的类中的postProcessMergedBeanDefinition方法
        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
      }
      catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                        "Post-processing of merged bean definition failed", ex);
      }
      mbd.postProcessed = true;
    }
  }

  // Eagerly cache singletons to be able to resolve circular references
  // even when triggered by lifecycle interfaces like BeanFactoryAware.
  // 判断bean是否存在循环依赖
  // 如果当前bean是单例,且支持循环依赖,且当前bean正在创建,通过往singletonFactories添加一个objectFactory,这样后期如果有其他bean依赖该bean 可以从singletonFactories获取到bean
  boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
  if (earlySingletonExposure) {
    if (logger.isDebugEnabled()) {
      logger.debug("Eagerly caching bean '" + beanName +
                   "' to allow for resolving potential circular references");
    }
    // 解决Spring循环依赖问题
    // 添加工厂对象到singletonFactories缓存中【提前暴露早期对象】
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  }

  // Initialize the bean instance.
  // 初始化bean实例
  Object exposedObject = bean;
  try {
    // 给已经已经初始化的属性赋值,包括完成bean的依赖注入
    populateBean(beanName, mbd, instanceWrapper);

    // 初始化bean实例
    exposedObject = initializeBean(beanName, exposedObject, mbd);
  }
  catch (Throwable ex) {
    if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
      throw (BeanCreationException) ex;
    }
    else {
      throw new BeanCreationException(
        mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
    }
  }

  // 解决循环依赖
  if (earlySingletonExposure) {
    Object earlySingletonReference = getSingleton(beanName, false);
    if (earlySingletonReference != null) {
      if (exposedObject == bean) {
        exposedObject = earlySingletonReference;
      }
      else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
        String[] dependentBeans = getDependentBeans(beanName);
        Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
        for (String dependentBean : dependentBeans) {
          if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
            actualDependentBeans.add(dependentBean);
          }
        }
        if (!actualDependentBeans.isEmpty()) {
          throw new BeanCurrentlyInCreationException(beanName,
                                                     "Bean with name '" + beanName + "' has been injected into other beans [" +
                                                     StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                                     "] in its raw version as part of a circular reference, but has eventually been " +
                                                     "wrapped. This means that said other beans do not use the final version of the " +
                                                     "bean. This is often the result of over-eager type matching - consider using " +
                                                     "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
        }
      }
    }
  }

  // Register bean as disposable.
  // 销毁
  try {
    registerDisposableBeanIfNecessary(beanName, bean, mbd);
  }
  catch (BeanDefinitionValidationException ex) {
    throw new BeanCreationException(
      mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  }

  return exposedObject;
}

applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
  for (BeanPostProcessor bp : getBeanPostProcessors()) {
    if (bp instanceof MergedBeanDefinitionPostProcessor) {
      MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
      bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
    }
  }
}

bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName)
MergedBeanDefinitionPostProcessor的实现类可以用来处理@Autowired、@Value、@PostConstruct、@PreDestroy、@Scheduled等Spring提供的注解

下面以实现类AutowiredAnnotationBeanPostProcessor用来处理@Autowired、@Value注解举例

当bdp的实现类是AutowiredAnnotationBeanPostProcessor时,将调用AutowiredAnnotationBeanPostProcessor重写的postProcessMergedBeanDefinition方法

@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
	InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
	metadata.checkConfigMembers(beanDefinition);
}

findAutowiringMetadata(beanName, beanType, null)

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
	// Fall back to class name as cache key, for backwards compatibility with custom callers.
	String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
	// Quick check on the concurrent map first, with minimal locking.
	InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
	if (InjectionMetadata.needsRefresh(metadata, clazz)) {
		synchronized (this.injectionMetadataCache) {
			metadata = this.injectionMetadataCache.get(cacheKey);
			if (InjectionMetadata.needsRefresh(metadata, clazz)) {
				if (metadata != null) {
					metadata.clear(pvs);
				}

				// 解析等待依赖注入类的所有属性,构建InjectionMetadata对象,它是通过分析类中所有属性和所有方法中是否有该注解
				metadata = buildAutowiringMetadata(clazz);
				this.injectionMetadataCache.put(cacheKey, metadata);
			}
		}
	}
	return metadata;
}

buildAutowiringMetadata(clazz)

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
	List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
	Class<?> targetClass = clazz;

	do {
		final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

		// 扫描所有属性
		ReflectionUtils.doWithLocalFields(targetClass, field -> {
			// 通过分析属于一个字段的所有注解来查找@Autowired注解
			AnnotationAttributes ann = findAutowiredAnnotation(field);

			if (ann != null) {
				if (Modifier.isStatic(field.getModifiers())) {
					if (logger.isWarnEnabled()) {
						logger.warn("Autowired annotation is not supported on static fields: " + field);
					}
					return;
				}
				boolean required = determineRequiredStatus(ann);
				currElements.add(new AutowiredFieldElement(field, required));
			}
		});

		// 扫描所有方法
		ReflectionUtils.doWithLocalMethods(targetClass, method -> {
			Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
			if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
				return;
			}

			// 通过分析属于一个方法的所有注解来查找@Autowired注解
			AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);

			if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
				if (Modifier.isStatic(method.getModifiers())) {
					if (logger.isWarnEnabled()) {
						logger.warn("Autowired annotation is not supported on static methods: " + method);
					}
					return;
				}
				if (method.getParameterCount() == 0) {
					if (logger.isWarnEnabled()) {
						logger.warn("Autowired annotation should only be used on methods with parameters: " +
								method);
					}
				}
				boolean required = determineRequiredStatus(ann);
				PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
				currElements.add(new AutowiredMethodElement(method, required, pd));
			}
		});

		elements.addAll(0, currElements);
		targetClass = targetClass.getSuperclass();
	}
	while (targetClass != null && targetClass != Object.class);

	return new InjectionMetadata(clazz, elements);
}

populateBean(beanName, mbd, instanceWrapper)

/**
 * 给已经已经初始化的属性赋值,包括完成bean的依赖注入
 * 这个方法最重要就是最后一个方法applyPropertyValues(beanName, mbd, bw, pvs):为属性赋值
 */
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {

    // 这一大段代码省略
    ......
    
	// 为属性赋值
	if (pvs != null) {
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

applyPropertyValues(beanName, mbd, bw, pvs)

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {

    // 这一大段代码省略
    ......

	// 为当前bean中属性赋值,包括依赖注入的属性
	Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
	
	// 这一大段代码省略
    ......
}

valueResolver.resolveValueIfNecessary(pv, originalValue)

/**
 * 如果当前初始化的bean有属性需要注入的,将会调用resolveReference(argName, ref)来返回需要注入的bean
 */
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
	// 获取需要依赖注入属性的值
	if (value instanceof RuntimeBeanReference) {
		RuntimeBeanReference ref = (RuntimeBeanReference) value;
		return resolveReference(argName, ref);
	}
	
	// 这一大段代码省略
    ......
}

resolveReference(argName, ref)

private Object resolveReference(Object argName, RuntimeBeanReference ref) {
	try {
		Object bean;
		String refName = ref.getBeanName();
		refName = String.valueOf(doEvaluate(refName));
		if (ref.isToParent()) {
			if (this.beanFactory.getParentBeanFactory() == null) {
				throw new BeanCreationException(
						this.beanDefinition.getResourceDescription(), this.beanName,
						"Can't resolve reference to bean '" + refName +
								"' in parent factory: no parent factory available");
			}
			bean = this.beanFactory.getParentBeanFactory().getBean(refName);
		}
		else {
		    // 当前初始化bean主要为属性注入另外一个bean,调用getBean()方法获取需要注入的bean,最终注入到属性中
			bean = this.beanFactory.getBean(refName);
			this.beanFactory.registerDependentBean(refName, this.beanName);
		}
		if (bean instanceof NullBean) {
			bean = null;
		}
		return bean;
	}
	catch (BeansException ex) {
		throw new BeanCreationException(
				this.beanDefinition.getResourceDescription(), this.beanName,
				"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
	}
}

getSingleton(beanName, singletonFactory)

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  Assert.notNull(beanName, "Bean name must not be null");
  synchronized (this.singletonObjects) {
    // 尝试从一级缓存中获取bean实例
    Object singletonObject = this.singletonObjects.get(beanName);

    if (singletonObject == null) {
      if (this.singletonsCurrentlyInDestruction) {
        throw new BeanCreationNotAllowedException(beanName,
                                                  "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                                                  "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
      }
      if (logger.isDebugEnabled()) {
        logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
      }

      // 将beanName添加到singletonsCurrentlyInCreation集合中,
      // 用于表明beanName对应的bean正在创建中
      beforeSingletonCreation(beanName);
      boolean newSingleton = false;
      boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
      if (recordSuppressedExceptions) {
        this.suppressedExceptions = new LinkedHashSet<>();
      }

      try {
        // 调用FactoryBean接口中的getObject()方法获取bean实例
        singletonObject = singletonFactory.getObject();
        newSingleton = true;
      }
      catch (IllegalStateException ex) {
        // Has the singleton object implicitly appeared in the meantime ->
        // if yes, proceed with it since the exception indicates that state.
        singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
          throw ex;
        }
      }
      catch (BeanCreationException ex) {
        if (recordSuppressedExceptions) {
          for (Exception suppressedException : this.suppressedExceptions) {
            ex.addRelatedCause(suppressedException);
          }
        }
        throw ex;
      }
      finally {
        if (recordSuppressedExceptions) {
          this.suppressedExceptions = null;
        }

        // 从singletonsCurrentlyInCreation实现FactoryBean接口中的bean,表明实现了FactoryBean接口的bean获取完毕
        afterSingletonCreation(beanName);
      }
      if (newSingleton) {
        // 最后将singletonObject添加到singletonObjects一级缓存中,同时将二级、三级缓存中的bean删除
        addSingleton(beanName, singletonObject);
      }
    }
    return singletonObject;
  }
}

addSingleton(beanName, singletonObject)

/**
 * 将singletonObject添加到singletonObjects一级缓存中,同时将二级、三级缓存中的bean删除
 */
protected void addSingleton(String beanName, Object singletonObject) {
	synchronized (this.singletonObjects) {
		this.singletonObjects.put(beanName, singletonObject);
		this.singletonFactories.remove(beanName);
		this.earlySingletonObjects.remove(beanName);
		this.registeredSingletons.add(beanName);
	}
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以在 Spring 配置文件中使用 `default-lazy-init` 属性来设置全局的延迟初始化。例如: ``` <beans default-lazy-init="true"> <!-- 其他 bean 定义 --> </beans> ``` 这将会导致所有的 bean 都采用延迟初始化的方式,除非在单独的 bean 定义中显式地设置 `lazy-init` 属性为 `false`。 另外,也可以通过在类路径中添加 `META-INF/spring.factories` 文件,并在该文件中添加如下内容来设置全局的延迟初始化: ``` org.springframework.context.annotation.ConfigurationClassPostProcessor.registerLazyInitialization=true ``` 最后,还可以使用 Spring 的 `AbstractApplicationContext` 类的 `setDefaultLazyInitialization` 方法来设置全局的延迟初始化,例如: ``` AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.setDefaultLazyInitialization(true); context.register(AppConfig.class); context.refresh(); ``` ### 回答2: 在Spring中,可以通过配置来设置全局的延迟初始化。要实现这个目标,可以按照以下步骤进行操作。 首先,在Spring的配置文件中,可以通过`<beans>`标签来设置全局的延迟初始化策略。可以使用`default-lazy-init`属性来指定全局的延迟初始化行为。将其设置为`true`,表示所有的bean都将被延迟初始化;将其设置为`false`,表示所有的bean都将立即初始化。例如: ```xml <beans default-lazy-init="true"> <!-- bean definitions here --> </beans> ``` 其次,如果需要对特定的bean进行自定义的延迟初始化设置,可以在相应的bean定义中使用`lazy-init`属性进行配置。将其设置为`true`,表示该bean将被延迟初始化;将其设置为`false`,表示该bean将立即初始化。例如: ```xml <bean id="myBean" class="com.example.MyBean" lazy-init="true"> <!-- bean properties and configuration here --> </bean> ``` 通过上述两种方式,可以实现全局的延迟初始化设置。这样可以有效地控制bean的初始化时机,避免在应用启动过程中加载过多的bean,从而提高应用的性能和响应速度。 ### 回答3: 在Spring中,我们可以使用lazy-init属性来设置全局的延迟初始化。 延迟初始化意味着在第一次访问bean时才会创建实例。相反,如果不设置延迟初始化,Spring容器在启动时就会创建所有的bean实例。 要设置全局的延迟初始化,我们可以在Spring配置文件(通常是applicationContext.xml)中使用default-lazy-init属性。例如: <beans default-lazy-init="true"> <!-- bean definitions --> </beans> 在上面的示例中,默认的延迟初始化值设置为true,这意味着所有的bean都会被延迟初始化。如果想要某个特定的bean在启动时立即初始化,可以在其bean定义中明确设置lazy-init属性为false。 延迟初始化对于应用中一些不常用或资源消耗较大的bean很有用,可以提高应用的启动性能。但需要注意的是,如果一个bean在容器启动后需要立即使用,而它被延迟初始化了,那么可能会导致一些问题。因此,在选择是否延迟初始化时,需要仔细考虑应用的需求和性能权衡。 总结来说,要设置全局的延迟初始化,在Spring配置文件中使用default-lazy-init属性,并将其设为true。如果需要某个特定的bean立即初始化,可以在其bean定义中将lazy-init属性设为false。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值