Spring源码之Spring上下文环境的初始化流程(五)

前言:
此文非常长,可选择按小标题来看,后期会添加目录

在上一节Spring源码之AnnotatedBeanDefinitionReader的注册流程(四)
,解析完所有的类的注册后,开始初始化spring的上下文环境
以下是AnnotationConfigApplicationContext容器的类图

1.解析代码入口,下图第13行

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
/**
 * 先调用父类的构造方法:
 * 1.DefaultResourceLoader构造方法,初始化ClassLoader
 * 2.AbstractApplicationContext,初始化ResourcePatternResolver
 * 3.GenericApplicationContext,初始化一个DefaultListableBeanFactory
 */
   //有父类,先调用父类的构造方法,然后调用自己的构造方法
   //在自己的构造方法里初始化一个读取器和一个扫描器
   this();
   register(annotatedClasses);
   //初始化spring的环境
   refresh();
}

2.接下来详细解析spring初始化的源码
2.1AbstractApplicationContext#refresh,首先来看主流程的代码

public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      //准备工作:设置启动时间
      prepareRefresh();
      //刷新内部工厂:即获取新的工厂,销毁旧工厂
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      //配置BeanFactory
      prepareBeanFactory(beanFactory);
      try {
         //在子类中对beanFactory进行后置处理,目前没有具体逻辑
         postProcessBeanFactory(beanFactory);
         //执行BeanFactoryPostProcessor后置处理器的实现类,各种处理器将在后面专题来讲
         //此处可以理解为spring给我们提供了对beanFactory的扩展的入口
         invokeBeanFactoryPostProcessors(beanFactory);
         //注册BeanPostProcessor后置处理器的实现类,只是注册,没有执行,会在bean创建的时候执行
         registerBeanPostProcessors(beanFactory);
         //初始化Message源
         initMessageSource();
         //初始化消息广播器
         initApplicationEventMulticaster();
         //没有具体逻辑实现
         onRefresh();
         //将注册的Listener bean注册到消息广播器中
         registerListeners();
         //提前初始化单例bean(非惰性)
         finishBeanFactoryInitialization(beanFactory);
         //完成刷新,发出ContextRefreshEvent事件,并通知生命周期处理器LifecycleProcessor刷新过程
         finishRefresh();
      }catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization -cancelling refresh attempt: " + ex);
         }
         destroyBeans();
         cancelRefresh(ex);
         throw ex;
      } finally {
         resetCommonCaches();
      }
   }
}

小结:

1.刷新beanFactory前准备工作
2.刷新beanFactory
3.初始化配置beanFactory
4.调用BeanFactoryPostProcessor工厂后置处理器(执行)
5.注册BeanPostProcessor后置处理器(注册,此时不执行)
6.初始化单例bean(未被@Lazy注解标注的bean)
7.完成刷新,清理缓存等

2.2容器刷新前的准备工作: prepareRefresh()

protected void prepareRefresh() {
    //设置容器启动时间,以及容器的关闭,启动的标志位。
   this.startupDate = System.currentTimeMillis();
   this.closed.set(false);
   this.active.set(true);
   //日志打印
   if (logger.isInfoEnabled()) {
      logger.info("Refreshing " + this);
   }
   // Initialize any placeholder property sources in the context environment
   //此方法没有逻辑,spring希望在子类中来扩展初始化一些参数及上下文环境设置
   initPropertySources();
   // Validate that all properties marked as required are resolvable
   // see ConfigurablePropertyResolver#setRequiredProperties
   //校验是否存在一些必要的初始化参数
   getEnvironment().validateRequiredProperties();

   // Allow for the collection of early ApplicationEvents,
   // to be published once the multicaster is available...
   //初始化spring容器中的earlyApplicationEvents(用于存放一些早期的事件)
   this.earlyApplicationEvents = new LinkedHashSet<>();
}

2.3获取beanFactory对象: ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
因为咱们分析的spring容器是AnnotationConfigApplicationContext,他的beanFactory创建是在其父类创建

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //刷新工厂,不同容器工厂的创建方式不同,AnnotationConfigApplicationContext容器是在父类GenericApplicationContext中直接new的
   refreshBeanFactory();
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   if (logger.isDebugEnabled()) {
      logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
   }
   return beanFactory;
}
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");
   }
   this.beanFactory.setSerializationId(getId());
}

2.4配置beanFactory,prepareBeanFactory()

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // Tell the internal bean factory to use the context's class loader etc.
   //添加一个类加载器,加载器已在context的父类DefaultResourceLoader里创建
   beanFactory.setBeanClassLoader(getClassLoader());
   //添加一个bean表达式解释器
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   //对象与字符串之间的转换
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
   // Configure the bean factory with context callbacks.
   //添加后置处理器
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

   //设置忽略自动装配的Bean,不重要
   beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
   beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
   beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
   beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

   // BeanFactory interface not registered as resolvable type in a plain factory.
   // MessageSource registered (and found for autowiring) as a bean.
   //替换一些bean
   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.class, this);
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
   beanFactory.registerResolvableDependency(ApplicationContext.class, this);

   // Register early post-processor for detecting inner beans as ApplicationListeners.
   //不重要的后置处理器
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

   // Detect a LoadTimeWeaver and prepare for weaving, if found.
   if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      // Set a temporary ClassLoader for type matching.
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }

   // Register default environment beans.
   //注册一些系统配置,系统环境信息的bean
   if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
   }
   if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
   }
   if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
   }
}

2.5 工厂后置处理器执行invokeBeanFactoryPostProcessors(beanFactory)

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()));
   }
}
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
   // Invoke BeanDefinitionRegistryPostProcessors first, if any.
   //存储执行过的工厂后置处理器的beanName,主要是为了记录
   Set<String> processedBeans = new HashSet<>();
   //BeanDefinitionRegistry类型的beanFactory,就是可以操作BeanDefinition的beanFactory
   //这种beanFactory需要先执行BeanDefinitionRegistryPostProcessors后置处理器
   if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      //下面两个list存放外部定义的BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor
      //关于后置处理器,后面会详细介绍其作用,现在就可以看作是扩展beanFactory和context的一些类
      //BeanFactoryPostProcessor是给beanFactory添加或修改其内容
      //BeanDefinitionRegistryPostProcessor是给容器添加一些额外的组件
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                  (BeanDefinitionRegistryPostProcessor) postProcessor;
            //执行自定义的BeanDefinitionRegistryPostProcessor的子接口
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            //此行add到registryProcessors是为了后面执行父接口
            registryProcessors.add(registryProcessor);
         }
         else {
            regularPostProcessors.add(postProcessor);
         }
      }
      //放spring自己的BeanDefinitionRegistryPostProcessor
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
      /**
       * 后置处理器执行优先级
       * 下面三个优先级:
       * 1.实现PriorityOrdered
       * 2.实现Ordered
       * 3.没有实现上面两个接口
       */
       //执行三次for循环,每次只处理指定类型的处理器
      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
      //首先,从工厂中获取到BeanDefinitionRegistryPostProcessor类型的并实现了PriorityOrdered的后置处理器
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
         //判断类型是否匹配PriorityOrdered,就是这个bean是否实现了PriorityOrdered接口
         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            //放入List中
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            //将名字放入Set中
            processedBeans.add(ppName);
         }
      }
      //排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      //合并List内容:spring内部的加外部自定义的
      registryProcessors.addAll(currentRegistryProcessors);
      //循环执行BeanDefinitionRegistryPostProcessor类型的后置处理器
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();

      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      //其次,从工厂中获取到BeanDefinitionRegistryPostProcessor类型的并实现了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.
      //最后,执行所有的BeanDefinitionRegistryPostProcessor后置处理器
      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.
      //执行自定义的BeanDefinitionRegistryPostProcessors和spring自己的BeanDefinitionRegistryPostProcessors的父接口
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      //执行自定义的beanFactory后置处理器的方法
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
   }else {
      // Invoke factory processors registered with the context instance.
      //普通的beanFactory,就直接执行,他不会有BeanDefinitionRegistryPostProcessor后置处理器
      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!
   //执行beanFactory自己的BeanFactoryPostProcessor后置处理器,也是按顺序执行
   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();
}

invokeBeanFactoryPostProcessors(beanFactory)执行顺序小结

beanFactory放置spring自己的两种后置处理器,beanFactoryPostProcessors放置自定义的两种后置处理器
遵循的原则就是先执行BeanDefinitionRegistryPostProcessors,后执行BeanFactoryPostProcessor
1.执行自定义的BeanDefinitionRegistryPostProcessors的子接口
2.执行spring自己的BeanDefinitionRegistryPostProcessors的子接口(按顺序)
3.执行自定义的BeanDefinitionRegistryPostProcessors和spring自己的BeanDefinitionRegistryPostProcessors的父接口
4.执行自定义的BeanFactoryPostProcessor
5.执行spring自己的BeanFactoryPostProcessor(按顺序)

2.6.bean后置处理器注册registerBeanPostProcessors(beanFactory)

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

   //获取到程序员实现BeanPostProcessor接口的BeanName,遍历beanDefinitionNames集合获取
   //其中第二个参数true表示只取单例bean,第二个表示不取循环依赖的bean
   //其中已知的包括spring内部的BeanPostProcessor实现类(三个)的数组CommonAnnotationBeanPostProcessor,AutowiredAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
   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.
   int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
   //新增一个BeanPostProcessorChecker到beanFactory中的beanPostProcessors集合(默认有三个spring内部的)中
   //上面的beanProcessorTargetCount+1就是加的这个checker
   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)) {//PriorityOrdered优先级1
         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
         priorityOrderedPostProcessors.add(pp);
         //此处的意思就是要是实现了MergedBeanDefinitionPostProcessor接口就会放入internalPostProcessors这个内部的后置处理器集合,
         //后面代码会将这个集合重新注册一次,使其内部的后置处理器放置在beanPostProcessors集合的最后,在执行阶段也最后执行
         if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
         }
      }else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {//Ordered优先级2
         orderedPostProcessorNames.add(ppName);
      }else {//其他
         nonOrderedPostProcessorNames.add(ppName);
      }
   }

   // First, register the BeanPostProcessors that implement PriorityOrdered.
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   //注册PriorityOrdered优先级的后置处理器
   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

   // Next, register the BeanPostProcessors that implement 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);
   //注册Ordered优先级的后置处理器
   registerBeanPostProcessors(beanFactory, orderedPostProcessors);

   // Now, register all regular BeanPostProcessors.
   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);
   //重新注册spring内部的后置处理器
   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).
   //重新注册ApplicationListenerDetector处理器,使其放在beanPostProcessors集合的最后
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
private static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
   for (BeanPostProcessor postProcessor : postProcessors) {
      beanFactory.addBeanPostProcessor(postProcessor);
   }
}
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);
}

小结:

1.从beanDefinitionNames集合中获取实现类BeanPostProcessor接口的bean(只取单例,没有循环依赖的)
2.注册一个BeanPostProcessorChecker后置处理器,用于check
3.注册priorityOrdered优先级的后置处理器
4.注册Ordered优先级的后置处理器
5.注册常规后置处理器
6.重新注册内部的后置处理器
7.重新注册ApplicationListenerDetector后置处理器

2.7 初始化单例bean finishBeanFactoryInitialization(beanFactory)

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // Initialize conversion service for this context.
   //初始化容器中的类型转换服务(conversion service)
   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.
   //EmbeddedValueResolver处理字符串的一个类
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
   }
   
   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
   //LoadTimeWeaverAware加载时间织入bean初始化
   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.
   //冻结缓存所有的beanDefinition数据,不希望在初始化的过程中改变beanDefinition数据
   beanFactory.freezeConfiguration();

   // Instantiate all remaining (non-lazy-init) singletons.
   //重点:初始化所有的非懒加载单例bean
   beanFactory.preInstantiateSingletons();
}

实例化所有剩余的单例Bean#preInstantiateSingletons()

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

   // Iterate over a copy to allow for init methods which in turn register new bean definitions.
   // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
          //判断是不是FactoryBean,FactoryBean需要特殊处理
         //获取这个工厂bean本身需要在beanName前加&,不加的话就是获取的这个工厂bean里面的对象
         if (isFactoryBean(beanName)) {
             //获取到工厂bean本身
            //判断这个工厂bean是否需要马上初始化,还是在使用bean的时候才去初始化
            //isEagerInit为true,需要马上初始化,直接执行getBean
            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);
         }
      }
   }
   // Trigger post-initialization callback for all applicable beans...
   //所有bean初始化完成,回调实现了SmartInitializingSingleton接口的bean的后置处理方法
   for (String beanName : beanNames) {
       //获取bean
      Object singletonInstance = getSingleton(beanName);
      //判断其是否实现了SmartInitializingSingleton接口,即是否需要执行后置处理方法
      if (singletonInstance instanceof SmartInitializingSingleton) {
         final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
             //此处是Java安全管理器的使用,这里不作解释
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                //执行后置处理方法
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }else {
             //执行后置处理方法
            smartSingleton.afterSingletonsInstantiated();
         }
      }
   }
}

小结:

1.初始化所有的非懒加载的单例bean
  1.1.工厂bean的初始化
  1.2.普通bean的初始化
2.初始化完成后,回调实现了SmartInitializingSingleton接口的方法实现

接下来看重点方法getBean()

public Object getBean(String name) throws BeansException {
   return 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 {
   //1.如果是FactoryBean,会去掉Bean开头的&符号
   //2.存在别名的情况,获取到实际真实的beanName
   final String beanName = transformedBeanName(name);
   Object bean;

   // Eagerly check singleton cache for manually registered singletons.
   //先从缓存中获取,要是缓存中没有,则进行创建
   Object sharedInstance = getSingleton(beanName);
   if (sharedInstance != null && args == null) {
       //1.缓存中有
      if (logger.isDebugEnabled()) {
         if (isSingletonCurrentlyInCreation(beanName)) {
            logger.debug("Returning eagerly cached 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 + "'");
         }
      }
      //该方法是获取bean实例,下面有详解,大概分为两种方式
      //获取普通bean或者工厂bean本身就执行返回bean实例,获取工厂bean产生的实例则需要共工厂bean里获取
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   } else {
       //2.缓存中没有
      // Fail if we're already creating this bean instance:
      // We're assumably within a circular reference.
      //如果这个bean实例正在创建而且他是原型的那么就抛出异常
      if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
      }

      // Check if bean definition exists in this factory.
      //检查父容器里是否有该bean实例,有的话就不再创建
      BeanFactory parentBeanFactory = getParentBeanFactory();
      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);
         }
      }
      //小校验,如果已经创建过,则加入了alreadyCreated集合里
      if (!typeCheckOnly) {
         markBeanAsCreated(beanName);
      }

      try {
         final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         //校验beanDefinition是否为抽象,抽象则抛出异常
         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 {
                   //创建依赖bean,此处说明,在创建bean时候,发现有依赖,先创建依赖的bean
                  getBean(dep);
               }
               catch (NoSuchBeanDefinitionException ex) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
               }
            }
         }

         // Create bean instance.
         if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, () -> {
               try {
                   //创建bean的方法,重要方法来了,下面详解
                  return createBean(beanName, mbd, args);
               }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
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
         } else if (mbd.isPrototype()) {
            // It's a prototype -> create a new instance.
            //原型bean,那么重新创建一个bean
            Object prototypeInstance = null;
            try {
               beforePrototypeCreation(beanName);
               prototypeInstance = createBean(beanName, mbd, args);
            }finally {
               afterPrototypeCreation(beanName);
            }
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
         } else {
             //其他scope类型的bean创建
            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;
}

处理工厂bean与普通bean的方法getObjectForBeanInstance()

protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
   // Don't let calling code try to dereference the factory if the bean isn't a factory.
   if (BeanFactoryUtils.isFactoryDereference(name)) {
      //该方法是判断name咱们传入的beanName是否是以&开头,这里的beanName是真实的beanName
      //name以&开头,则说明需要获取factoryBean本身,然后做非空判断
      if (beanInstance instanceof NullBean) {
         return beanInstance;
      }
      if (!(beanInstance instanceof FactoryBean)) {
         throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
      }
   }

   // Now we have the bean instance, which may be a normal bean or a FactoryBean.
   //现在我们获取到的bean实例,可能是一个普通bean也可能是一个工厂bean
   // If it's a FactoryBean, we use it to create a bean instance, unless the
   // caller actually wants a reference to the factory.
   //如果是工厂bean,要是调用方不是想获取工厂bean本身那么我们可以用它来创建一个bean实例
   if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
      //此处是获取普通bean或者工厂bean本身
      return beanInstance;
   }
   //此处是获取工厂bean内的bean实例
   Object object = null;
   if (mbd == null) {
      object = getCachedObjectForFactoryBean(beanName);
   }
   if (object == null) {
      // Return bean instance from factory.
      FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
      // Caches object obtained from FactoryBean if it is a singleton.
      if (mbd == null && containsBeanDefinition(beanName)) {
         mbd = getMergedLocalBeanDefinition(beanName);
      }
      boolean synthetic = (mbd != null && mbd.isSynthetic());
      object = getObjectFromFactoryBean(factory, beanName, !synthetic);
   }
   return object;
}

重要的方法来了createBean(beanName, mbd, args)此方法会专门专题详解。

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.
   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.
      //给bean后置处理器创建代理对象的一个机会
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      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);
   }
}

2.8 finishRefresh()完成初始化,流程结束。

你可能感兴趣的:(Spring源码专题)