Bean的加载

211 阅读6分钟

Application

BeanFactory是一个bean的容器,负责bean的创建和管理。Application继承自BeanFactory,是BeanFactory的扩展升级版。

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

以ClassXmlApplicationContext类为切入点,分析bean的加载过程。

ClassPathXmlApplicationContext

ClassPathXmlApplicationContext的简化版的继承体系为:

BeanFactory
ApplicationContext
AbstractApplicationContext
ClassPathXmlApplicationContext

ClassPathXmlApplicationContext有两个主要的构造方法

/**
 * 该方法可以使用占位符设置配置文件路径
 *
 * @param configLocations 资源位置数组
 * @param refresh 是否自动刷新context,加载全部的bean以及创建所有的单例
 * @param parent 父context
 */
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
   super(parent);
   setConfigLocations(configLocations);
   if (refresh) {
      refresh();
   }
}

/**
 * 该方法不可以使用占位符设置配置文件路径
 *
 * @param paths 类路径中的相对(或绝对)的资源路径数组
 * @param clazz 基于给定路径要加载资源的类
 * @param parent 父context
 */
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, @Nullable ApplicationContext parent) throws BeansException {
   super(parent);
   Assert.notNull(paths, "Path array must not be null");
   Assert.notNull(clazz, "Class argument must not be null");
   this.configResources = new Resource[paths.length];
   for (int i = 0; i < paths.length; i++) {
      this.configResources[i] = new ClassPathResource(paths[i], clazz);
   }
   refresh();
}

super(parent)方法

super(parent)是由基类AbstractApplicationContext中实现,主要逻辑为执行无参构造方法和setParent()方法:

// ClassPathXmlApplicationContext调用super(parent)的基类方法
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
   this();
   setParent(parent);
}

// 类ResourcePatternResolver继承自ResourceLoader,是一个资源加载器
public AbstractApplicationContext() {
   this.resourcePatternResolver = getResourcePatternResolver();
}

// 获取一个Source加载器用于读入Spring Bean 定义资源文件
protected ResourcePatternResolver getResourcePatternResolver() {
   return new PathMatchingResourcePatternResolver(this);
}

// 设置父context,并合并与之关联的Environment
public void setParent(@Nullable ApplicationContext parent) {
   this.parent = parent;
   if (parent != null) {
      Environment parentEnvironment = parent.getEnvironment();
      if (parentEnvironment instanceof ConfigurableEnvironment) {
         getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
      }
   }
}

refresh()

refresh()方法是Spring Bean的核心,它是ClassPathXmlApplicationContext的父类AbstractApplicationContext的一个方法,用于刷新整个Spring上下文信息,定义了整个Spring上下文加载的流程。

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

      // 准备刷新上下文
      prepareRefresh();

      // 告诉子类刷新内部Bean Factory
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // 准备在该Context中使用的Bean Factory
      prepareBeanFactory(beanFactory);

      try {
         // 子类覆盖该方法对Bean Factory做额外处理
         postProcessBeanFactory(beanFactory);

         StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
         // 激活Bean Factory处理器
         invokeBeanFactoryPostProcessors(beanFactory);

         // 注册拦截bean创建的bean处理器
         registerBeanPostProcessors(beanFactory);
         beanPostProcess.end();

         // 初始化Message源
         initMessageSource();

         // 初始化事件广播器
         initApplicationEventMulticaster();

         // 子类初始化其他Bean
         onRefresh();

         // 检测listener bean并注册到消息广播器中
         registerListeners();

         // 初始化剩下全部的单实例(非惰性)
         finishBeanFactoryInitialization(beanFactory);

         // 发布相应的事件
         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();
         contextRefresh.end();
      }
   }
}

refresh()方法具有以下特点:

  1. 方法加锁,可以避免多线程同时刷新Spring上下文
  2. 使用了对象锁startupShutdownMonitor,而非在整个方法体上使用synchronized关键字,一方面减小了同步的范围,只对不能并发的代码块进行加锁,提高了整体代码运行效率;另一方面close()方法也是用了该对象锁,可以避免refresh()和close()方法的冲突
  3. 在refresh()方法中使用了很多子方法,使得整个方法流程清晰易懂,方便代码的可读性和可维护性

prepareRefresh()

prepareRefresh()是AbstractApplicationContext中的方法,该方法主要为刷新context做准备,包括设置启动时间,设置活跃标识,初始化属性配置

protected void prepareRefresh() {
   // 当前时间以及活跃标识
   this.startupDate = System.currentTimeMillis();
   this.closed.set(false);
   this.active.set(true);

   if (logger.isDebugEnabled()) {
      if (logger.isTraceEnabled()) {
         logger.trace("Refreshing " + this);
      }
      else {
         logger.debug("Refreshing " + getDisplayName());
      }
   }

   // 初始化任何在context环境中的占位符配置资源,由子类覆盖
   initPropertySources();

   // 验证所有的被标记为必须的属性是否可以解析
   getEnvironment().validateRequiredProperties();

   // 存储预刷新的Listener
   if (this.earlyApplicationListeners == null) {
      this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
   }
   else {
      // 重置application listenner
      this.applicationListeners.clear();
      this.applicationListeners.addAll(this.earlyApplicationListeners);
   }

   this.earlyApplicationEvents = new LinkedHashSet<>();
}

验证必须的属性是否可以解析,主要判断该属性是否为NULL

// AbstractApplication中的方法
public ConfigurableEnvironment getEnvironment() {
   if (this.environment == null) {
      this.environment = createEnvironment();
   }
   return this.environment;
}

// 创建ConfigurableEnvironment
protected ConfigurableEnvironment createEnvironment() {
   return new StandardEnvironment();
}

// 验证必须属性的方法是在StandardEnvironment的父类AbstractEnvironment中实现
public void validateRequiredProperties() throws MissingRequiredPropertiesException {
   this.propertyResolver.validateRequiredProperties();
}

// propertyResolver的validateRequiredProperties()方法在AbstractPropertyResolver中实现
public void validateRequiredProperties() {
   MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
   for (String key : this.requiredProperties) {
      // 获取属性,判断是否为null
      if (this.getProperty(key) == null) {
         ex.addMissingRequiredProperty(key);
      }
   }
   // 有缺失的属性,抛出异常
   if (!ex.getMissingRequiredProperties().isEmpty()) {
      throw ex;
   }
}

obtainFreshBeanFactory()

该方法是让子类刷新自己的Bean Factory,refreshBeanFactory()和getBeanFactory()都需要子类覆盖重写,两个方法均在子类AbstractRefreshableApplicationContext中实现。

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   refreshBeanFactory();
   return getBeanFactory();
}

refreshBeanFactory()方法用于关闭之前的bean factory,并初始化一个新的bean factory。

protected final void refreshBeanFactory() throws BeansException {
   if (hasBeanFactory()) {
      // 销毁所有的单例bean
      destroyBeans();
      // 关闭所有bean factory
      closeBeanFactory();
   }
   try {
      // 创建一个新的bean factory,类型为DefaultListableBeanFactory
      DefaultListableBeanFactory beanFactory = createBeanFactory();
      // 设置序列化ID
      beanFactory.setSerializationId(getId());
      // 设置bean factory的属性,包括allowBeanDefinitionOverriding和allowCircularReferences 
      customizeBeanFactory(beanFactory);
      // 将BeanDefinition加载到bean factory中。
      loadBeanDefinitions(beanFactory);
      this.beanFactory = beanFactory;
   }
   catch (IOException ex) {
      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
   }
}

加载BeanDefinition的方法loadBeanDefinitions()是在AbstractXmlApplicationContext类中实现的,该方法传入了上诉创建的DefaultListableBeanFactory,并且初始化一个XML解析器,再初始化一些环境,资源加载器,实体解析器等,最后再loadBeanDefinitions()方法中加载bean。

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
   // 创建一个新的BeanDefinition读取器,即XML解析器
   XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

   // Configure the bean definition reader with this context's
   // resource loading environment.
   // 设置环境
   beanDefinitionReader.setEnvironment(this.getEnvironment());
   // 设置资源加载器
   beanDefinitionReader.setResourceLoader(this);
   // 设置实体解析求
   beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

   // 子类提供的自定义reader初始化方法
   initBeanDefinitionReader(beanDefinitionReader);
   // 加载bean
   loadBeanDefinitions(beanDefinitionReader);
}

// AbstractXmlApplicationContext类中的方法
// getConfigResources()和getConfigLocations()对应着ClassPathXmlApplicationContext的两个构造函数
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
   Resource[] configResources = getConfigResources();
   if (configResources != null) {
      reader.loadBeanDefinitions(configResources);
   }
   String[] configLocations = getConfigLocations();
   if (configLocations != null) {
      reader.loadBeanDefinitions(configLocations);
   }
}

// AbstractBeanDefinitionReader中的加载bean方法
// 该方法主要完成两件事
// (1) 使用resourceLoader加载资源
// (2) 调用XmlBeanDefinitionReader中的loadBeanDefinitions()方法解析bean
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
   ResourceLoader resourceLoader = getResourceLoader();
   if (resourceLoader == null) {
      throw new BeanDefinitionStoreException(
            "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
   }

   if (resourceLoader instanceof ResourcePatternResolver) {
      // Resource pattern matching available.
      try {
         Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
         int count = loadBeanDefinitions(resources);
         if (actualResources != null) {
            Collections.addAll(actualResources, resources);
         }
         if (logger.isTraceEnabled()) {
            logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
         }
         return count;
      }
      catch (IOException ex) {
         throw new BeanDefinitionStoreException(
               "Could not resolve bean definition resource pattern [" + location + "]", ex);
      }
   }
   else {
      // Can only load single resources by absolute URL.
      Resource resource = resourceLoader.getResource(location);
      int count = loadBeanDefinitions(resource);
      if (actualResources != null) {
         actualResources.add(resource);
      }
      if (logger.isTraceEnabled()) {
         logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
      }
      return count;
   }
}

// XmlBeanDefinitionReader类中的加载bean的具体实现
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
   Assert.notNull(encodedResource, "EncodedResource must not be null");
   if (logger.isTraceEnabled()) {
      logger.trace("Loading XML bean definitions from " + encodedResource);
   }

   Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

   if (!currentResources.add(encodedResource)) {
      throw new BeanDefinitionStoreException(
            "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
   }

   // 将资源文件转换为类型为InputStream的I/O流
   // getInputStream()是在ClassPathResource中实现的,将XML转为InputStream
   try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
      // 从InputStream中得到xML的解析源
      InputSource inputSource = new InputSource(inputStream);
      // 设置inputSource的编码
      if (encodedResource.getEncoding() != null) {
         inputSource.setEncoding(encodedResource.getEncoding());
      }
      // 加载bean
      return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
   }
   catch (IOException ex) {
      throw new BeanDefinitionStoreException(
            "IOException parsing XML document from " + encodedResource.getResource(), ex);
   }
   finally {
      currentResources.remove(encodedResource);
      if (currentResources.isEmpty()) {
         this.resourcesCurrentlyBeingLoaded.remove();
      }
   }
}

// XmlBeanDefinitionReader类中方法
// 
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
      throws BeanDefinitionStoreException {

   try {
      // 转换为Document对象
      Document doc = doLoadDocument(inputSource, resource);
      // 对bean进行解析
      int count = registerBeanDefinitions(doc, resource);
      if (logger.isDebugEnabled()) {
         logger.debug("Loaded " + count + " bean definitions from " + resource);
      }
      return count;
   }
   catch (BeanDefinitionStoreException ex) {
      throw ex;
   }
   catch (SAXParseException ex) {
      throw new XmlBeanDefinitionStoreException(resource.getDescription(),
            "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
   }
   catch (SAXException ex) {
      throw new XmlBeanDefinitionStoreException(resource.getDescription(),
            "XML document from " + resource + " is invalid", ex);
   }
   catch (ParserConfigurationException ex) {
      throw new BeanDefinitionStoreException(resource.getDescription(),
            "Parser configuration exception parsing XML from " + resource, ex);
   }
   catch (IOException ex) {
      throw new BeanDefinitionStoreException(resource.getDescription(),
            "IOException parsing XML document from " + resource, ex);
   }
   catch (Throwable ex) {
      throw new BeanDefinitionStoreException(resource.getDescription(),
            "Unexpected exception parsing XML document from " + resource, ex);
   }
}

obtainFreshBeanFactory()通过加载XML文件,将XML文件解析成对应的BeanDefinition,完成了Bean的加载和注册,并且这些bean都会被注册到DefinitionListableBeanFactory中。

prepareBeanFactory()

该方法主要配置BeanFactory的上下文特征,例如上下文的类加载器和预处理器

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // 设置beanfactorty的classLoader为当前context的classLoader
   beanFactory.setBeanClassLoader(getClassLoader());
   // 支持使用SpEL表达式
   if (!shouldIgnoreSpel) {
      beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   }
   // 设置PropertyEditorRegistrar,将xml解析出来的bean属性和对应的Java类型做转换
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

   // 添加后置处理器ApplicationContextAwareProcessor,在bean初始化后自动执行各个Aware接口的set方法
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
   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.ignoreDependencyInterface(ApplicationStartupAware.class);

   // 预先设置用于自依赖注入的接口对象
   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.class, this);
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
   beanFactory.registerResolvableDependency(ApplicationContext.class, this);

   // 注册事件监听器
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

   // 如果存在LoadTimeWeaver这个bean,则增加对应的后置处理器
   if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }

   // 添加默认的系统环境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());
   }
   if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
      beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
   }
}

该方法主要在以下方法进行了扩展:

  1. 对SPEL语言的支持
  2. 增加对属性编辑器的支持
  3. 增加对一些内置类的支持,如EnvironmentAware、MessageSourceAware的注入
  4. 设置了依赖功能可忽略的接口
  5. 注册一些固定依赖的属性
  6. 如果存在loadTimeWeaver这个Bean,则增加对应的后置处理器
  7. 将相关环境变量及属性以单例模式注册

postProcessBeanFactory()

该方法为抽象方法,由子类覆盖重写。所有的Bean的定义已经加载完成,但还没有实例化,这一步可以修改bean的定义或者增加自定义的bean,该方法主要是承接上文的prepareBeanFactory()方法,增加了一些后置处理器,

invokeBeanFactoryPostProcessors()

该方法按照给定的显示顺序实例化并调用所有注册的实现BeanFactoryPostProcessor接口的bean,而ClassPathXmlApplicationContext类中的BeanFactoryPostProcessor是空,即不执行。

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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }
}

registerBeanPostProcessors()

该方法按照给定的顺序实例化并注册所有实现BeanPostProcessors接口的类。

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

initMessageSource()

在 Spring 容器中初始化一些国际化相关的属性 。

initApplicationEventMulticaster()

该方法初始化ApplicationEventMulticaster(事件广播器)。

protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   // 默认使用内置的事件广播器
   if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      if (logger.isTraceEnabled()) {
         logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
      }
   }
   else {
      // 创建一个事件广播器
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      if (logger.isTraceEnabled()) {
         logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
               "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
      }
   }
}

onRefresh()

模块方法,可用于refresh动作的扩展,默认为空实现。

registerListeners()

该方法添加实现ApplicationListener接口的bean作为监听器,并且不影响可以作为监听器但不是bean的监听器。

protected void registerListeners() {
   // 首先注册指定的静态事件监听器
   for (ApplicationListener<?> listener : getApplicationListeners()) {
      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // 其次,注册普通的事件监听器
   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
   for (String listenerBeanName : listenerBeanNames) {
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
   }

   // 如果有早期事件的话,进行事件广播
   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
   this.earlyApplicationEvents = null;
   if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
   }
}

finishBeanFactoryInitialization()

该方法初始化所有剩余的单例bean,实例化BeanFactory中已经被注册但是还未实例化的所有实例(懒加载的不需要实例化),主要操作时BeanFactory中的preInstantiateSingletons()方法,该方法分为两部份:

  1. 遍历已经解析出来的所有beanDefinitionNames,如果该BeanDefinition不是抽象类,是单例且没有设置懒加载,则进行实例化和初始化
  2. 遍历解析出来的beanDefinitionNams,如果获得的单例是SmartInitializingSingleton的实现类,则会执行afterSingletonsInstantiated方法,该方法调用指挥发生在启动阶段,后续懒加载对象再初始化时,不会再进行回调
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // 判断有无ConversionService(bean属性类型转换服务接口),并初始化
   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));
   }

   // 如果beanFactory中不包含EmbeddedValueResolver,则向其中添加一个EmbeddedValueResolver
   // EmbeddedValueResolver-->解析bean中的占位符和表达式
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
   }

   // 初始化LoadTimeWeaverAware类型的bean
   // LoadTimeWeaverAware-->加载Spring Bean时织入第三方模块,如AspectJ
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }

   // 释放临时类加载器
   beanFactory.setTempClassLoader(null);

   // 冻结缓存的BeanDefinition元数据
   beanFactory.freezeConfiguration();

   // 初始化其他的非延迟加载的单例bean
   beanFactory.preInstantiateSingletons();
}

finishRefresh()

该方法完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知。

protected void finishRefresh() {
   // 情况资源缓存
   clearResourceCaches();

   // 初始化生命周期处理器
   initLifecycleProcessor();

   // 调用生命周期处理器的onRefresh方法
   getLifecycleProcessor().onRefresh();

   // 推送容器刷新事件
   publishEvent(new ContextRefreshedEvent(this));

   // Participate in LiveBeansView MBean, if active.
   if (!NativeDetector.inNativeImage()) {
      LiveBeansView.registerApplicationContext(this);
   }
}