spring源码分析之上下文构建

news/2024/5/18 12:16:41

源码分析之上下文构建

以ClassPathXmlApplicationContext为例来说明

ApplicationContext context = new ClassPathXmlApplicationContext("spring-lifecycle.xml");

一个简单地创建ApplicationContext实例的方法,spring会做什么事呢?

// this(new String[] {configLocation}, true, null);
// refresh为true,parent为null
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
      throws BeansException 
{

   super(parent);
   // 为上下文设置配置文件的位置
   setConfigLocations(configLocations);
   if (refresh) {
      // 调用org.springframework.context.support.AbstractApplicationContext#refresh,刷新上下文,进行IOC容器的初始化
      refresh();
   }
}

spring在初始化上下文的最重要的方法就是这个refresh()方法了

refresh方法

public void refresh() throws BeansException, IllegalStateException {
  //容器重启同步监控锁,防止刷新进行到一半被重复执行
   synchronized (this.startupShutdownMonitor) {
      // 准备应用上下文,填充配置文件占位符,记录容器启动时间和启动状态
      prepareRefresh();

    
     // 刷新内部bean factory,即在子类中启动refreshBeanFactory()的地方,创建DefaultListableBeanFactory工厂,根据配置文件生成BeanDefinition,完成配置文件定义到注册表BeanDefinitionRegistry注册bean的流程,此时对象还未被创建
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // 对beanFactory进行功能填充,配置类加载器,定制特殊bean,添加BeanPostProcessor可供回调
      prepareBeanFactory(beanFactory);

      try {
        // 设置BeanFactory后置处理,工厂加载完配置,初始化之前回调PostProcessBeanFactory,作为工厂扩展功能,子类想在bean定义加载完成后,开始初始化上下文之前做一些特殊逻辑
         postProcessBeanFactory(beanFactory);

         // 调用BeanFactory的后置处理器,这些后处理器是在Bean定义中向容器注册的,如PropertyPlaceholderConfigurer就是在此处调用替换掉${}占位符的内容的
         invokeBeanFactoryPostProcessors(beanFactory);

         // 注册Bean的后置处理器,bean扩展:postProcessBeforeInitialization和postProcessAfterInitialization,分别在Bean初始化之前和初始化之后得到执行,如AutowiredAnnotationBeanPostProcessor实现@Autowired注解功能
         registerBeanPostProcessors(beanFactory);

         //初始化MessageSource对象,国际化
         initMessageSource();

         // 初始化上下文中的事件机制
         initApplicationEventMulticaster();

         // 初始化其他的特殊Bean,空方法,留给子类扩展
         onRefresh();

         // 注册监听器,检查监听Bean并且将这些Bean向容器注册
         registerListeners();

         // 实例化工厂注册表里所有的(non-lazy-init)单例bean,填充属性,初始化实例(调用init-method方法),调用BeanPostProcessor对实例bean进行后置处理
         finishBeanFactoryInitialization(beanFactory);

         //  发布容器事件,完成刷新
         finishRefresh();
      }

      catch (BeansException ex) {
         
     // 为防止资源占用,如果出现异常销毁已经创建好的单例bean
         destroyBeans();
    // 重置active标志
         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();
      }
   }
}

prepareRefresh初始化

容器初始化之前的初始化工作

protected void prepareRefresh() {
   // Switch to active.
   this.closed.set(false);
   this.active.set(true);

   // Initialize any placeholder property sources in the context environment.
  // 初始化环境资源
   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...
  // 创建监听器事件的集合
   this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

obtainFreshBeanFactory创建BeanFactory

创建BeanFactory,实现BeanFactory的全部功能

// org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   // org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory,关闭原始的beanFactory,并创建新的BeanFactory
   refreshBeanFactory();
   //返回创建的新工厂
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   
   return beanFactory;
}
refreshBeanFactory

org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory方法,关闭原始的beanFactory,并创建新的BeanFactory

protected final void refreshBeanFactory() throws BeansException {
  // 如果存在BeanFactory,则进行销毁并关闭该BeanFactory
   if (hasBeanFactory()) {
      destroyBeans();
      closeBeanFactory();
   }
   try {
     // 创建DefaultListableBeanFactory
      DefaultListableBeanFactory beanFactory = createBeanFactory();
      beanFactory.setSerializationId(getId());
     //设置一些属性值  容器是否允许对象覆盖allowBeanDefinitionOverriding,循环依赖allowCircularReferences
      customizeBeanFactory(beanFactory);
      // 读取xml配置文件,载入BeanDefinition信息,存储在beanDefinitionMap中
     // 在DefaultListableBeanFactory类中定义的private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(256);
      loadBeanDefinitions(beanFactory);
      this.beanFactory = beanFactory;
   }
   catch (IOException ex) {
      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
   }
}
createBeanFactory方法

实例化DefaultListableBeanFactory

protected DefaultListableBeanFactory createBeanFactory() {
   return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}

DefaultListableBeanFactory继承了AbstractAutowireCapableBeanFactory类,

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
      implements ConfigurableListableBeanFactoryBeanDefinitionRegistrySerializable
public AbstractAutowireCapableBeanFactory() {
   super();
  // 忽略给定接口的自动装配功能,这些接口spring会进行特殊处理
   ignoreDependencyInterface(BeanNameAware.class);
   ignoreDependencyInterface(BeanFactoryAware.class);
   ignoreDependencyInterface(BeanClassLoaderAware.class);
}
loadBeanDefinitions方法

org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions方法,读取xml配置文件,载入BeanDefinition信息,存储在beanDefinitionMap中

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
   // Create a new XmlBeanDefinitionReader for the given BeanFactory.
  // 进行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));

   // Allow a subclass to provide custom initialization of the reader,
   // then proceed with actually loading the bean definitions.
   initBeanDefinitionReader(beanDefinitionReader);
  // 获取对XML文件的验证模式
  // 加载XML文件,并得到对应的Document
  // 根据返回的Document注册Bean,会循环调用loadBeanDefinitions方法->其内调用doLoadBeanDefinitions->调用registerBeanDefinitions
   loadBeanDefinitions(beanDefinitionReader);
}
registerBeanDefinitions

org.springframework.beans.factory.xml.XmlBeanDefinitionReader#registerBeanDefinitions方法来进行解析和注册BeanDefinitions

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
  // DefaultBeanDefinitionDocumentReader实例化BeanDefinitionDocumentReader
   BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
  // 记录统计前的BeanDefinition的加载个数
   int countBefore = getRegistry().getBeanDefinitionCount();
  // 1.createReaderContext方法会初始化NamespaceHandlerReslver
  // 2.registerBeanDefinitions加载及注册bean,调用org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions方法
   documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
  // 本次加载的BeanDefinition个数
   return getRegistry().getBeanDefinitionCount() - countBefore;
}

1.createReaderContext流程

public XmlReaderContext createReaderContext(Resource resource) {
  // getNamespaceHandlerResolver方法会进行创建解析器createDefaultNamespaceHandlerResolver
   return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
         this.sourceExtractor, this, getNamespaceHandlerResolver());
}

// getNamespaceHandlerResolver调用
protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
  // 实例化DefaultNamespaceHandlerResolver,设置handlerMappingsLocation路径为META-INF/spring.handlers
  return new DefaultNamespaceHandlerResolver(getResourceLoader().getClassLoader());
 }

2.registerBeanDefinitions在进行xml读取注册

// 处理xml前  空方法
preProcessXml(root);
// 2.1进行xml读取
parseBeanDefinitions(root, this.delegate);
// 处理xml后  空方法
postProcessXml(root);

2.1parseBeanDefinitions方法

在进行xml处理时,对于不同的标签会进行不同的处理

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
  // 判断是不是默认命名空间的(http://www.springframework.org/schema/beans)
   if (delegate.isDefaultNamespace(root)) {
      NodeList nl = root.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
         Node node = nl.item(i);
         if (node instanceof Element) {
            Element ele = (Element) node;
           // 2.1.1.spring的默认标签,默认标签包含了import、alias、bean、beans
            if (delegate.isDefaultNamespace(ele)) {
              // 2.1.2.解析各个标签中的属性,属于xml解析范围,不在进行深入
               parseDefaultElement(ele, delegate);
            }
            else {
              // 自定义标签,如aop、mvc、tx等
               delegate.parseCustomElement(ele);
            }
         }
      }
   }
   else {
     // 自定义标签
      delegate.parseCustomElement(root);
   }
}

2.1.1 默认标签

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
   if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { // import
      importBeanDefinitionResource(ele);
   }
   else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { // alias
      processAliasRegistration(ele);
   }
   else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { // bean
     // 2.1.1.1  进行bean注册
      processBeanDefinition(ele, delegate);
   }
   else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { // beans
      // recurse
      doRegisterBeanDefinitions(ele);
   }
}

2.1.2 自定义标签

public BeanDefinition parseCustomElement(Element ele) {
   return parseCustomElement(ele, null);
}

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
  // 获取命名空间
  String namespaceUri = getNamespaceURI(ele);
  // 根据上述META-INF/spring.handlers文件进行映射,找到对应的handler,并进行初始化
  NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
  if (handler == null) {
   
   return null;
  }
  // 进行解析
  return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
 }

2.1.1.1 进行bean注册,根据beanName注册BeanDefinition

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
      throws BeanDefinitionStoreException 
{

   Assert.hasText(beanName, "Bean name must not be empty");
   Assert.notNull(beanDefinition, "BeanDefinition must not be null");

   if (beanDefinition instanceof AbstractBeanDefinition) {
      try {
        // 注册前的校验,主要是校验AbstractBeanDefinition属性中的methodOverrides和factoryMethodName
         ((AbstractBeanDefinition) beanDefinition).validate();
      }
      catch (BeanDefinitionValidationException ex) {
         throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
               "Validation of bean definition failed", ex);
      }
   }

   BeanDefinition oldBeanDefinition;
 // 从beanDefinitionMap中获取该beanName对应的实例
   oldBeanDefinition = this.beanDefinitionMap.get(beanName);
  // 如果该beanName已经注册过,需要进行处理
   if (oldBeanDefinition != null) {
     // 如果不允许覆盖则抛出异常
      if (!isAllowBeanDefinitionOverriding()) {
         throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
               "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
               "': There is already [" + oldBeanDefinition + "] bound.");
      }
      else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
         // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
         
      }
      else if (!beanDefinition.equals(oldBeanDefinition)) {
         
      }
      else {
         
      }
     // 进行覆盖
      this.beanDefinitionMap.put(beanName, beanDefinition);
   }
   else {
      if (hasBeanCreationStarted()) {
         // Cannot modify startup-time collection elements anymore (for stable iteration)
        // 防止map并发修改
         synchronized (this.beanDefinitionMap) {
            this.beanDefinitionMap.put(beanName, beanDefinition);
            List<String> updatedDefinitions = new ArrayList<String>(this.beanDefinitionNames.size() + 1);
            updatedDefinitions.addAll(this.beanDefinitionNames);
            updatedDefinitions.add(beanName);
            this.beanDefinitionNames = updatedDefinitions;
            if (this.manualSingletonNames.contains(beanName)) {
               Set<String> updatedSingletons = new LinkedHashSet<String>(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 (oldBeanDefinition != null || containsSingleton(beanName)) {
      resetBeanDefinition(beanName);
   }
}

prepareBeanFactory功能填充

对beanFactory的功能扩展

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // Tell the internal bean factory to use the context's class loader etc.
  // 设置类加载器
   beanFactory.setBeanClassLoader(getClassLoader());
  // 设置beanFactory的表达式语言处理器SPEL
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  // 设置PropertyEditor属性编辑器
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

  // 添加ApplicationContextAwareProcessor处理器  invokeAwareInterfaces方法,用于在前置处理器中执行EnvironmentAware#setEnvironment,EmbeddedValueResolverAware#setEmbeddedValueResolver,ResourceLoaderAware#setResourceLoader,ApplicationEventPublisherAware#setApplicationEventPublisher,MessageSourceAware#setMessageSource,ApplicationContextAware#setApplicationContext
   // Configure the bean factory with context callbacks.
   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 interface not registered as resolvable type in a plain factory.
   // MessageSource registered (and found for autowiring) as a bean.
  // 设置几个自动装配的特殊规则
   beanFactory.registerResolvableDependency(BeanFactory.classbeanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.classthis);
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.classthis);
   beanFactory.registerResolvableDependency(ApplicationContext.classthis);

   // Register early post-processor for detecting inner beans as ApplicationListeners.
  // 添加BeanPostProcessor
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

  // 增加对AspectJ的支持
   // 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()));
   }

  // 注册默认的系统环境bean
   // Register default environment beans.
   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());
   }
}

BeanFactory 后处理器

// Allows post-processing of the bean factory in context subclasses.
// 注册beanFactory后处理器
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
// 执行beanFactory后处理器
invokeBeanFactoryPostProcessors(beanFactory);
invokeBeanFactoryPostProcessors
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.
   Set<String> processedBeans = new HashSet<String>();
// 对BeanDefinitionRegistry进行处理
   if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
   // 注册BeanFactoryPostProcessor后处理器
      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                  (BeanDefinitionRegistryPostProcessor) postProcessor;
           // BeanDefinitionRegistryPostProcessor类型的后处理器,需要进行特殊处理,先调用postProcessBeanDefinitionRegistry方法
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            registryProcessors.add(registryProcessor);
         }
         else {
           // 常规的BeanFactoryPostProcessor
            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<BeanDefinitionRegistryPostProcessor>();

      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
     // 执行 BeanDefinitionRegistryPostProcessor类型的后处理器
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.classtruefalse);
      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);
     // 执行BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();

      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
     // 执行 BeanDefinitionRegistryPostProcessor类型的后处理器
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.classtruefalse);
      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);
     // 执行BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
      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.classtruefalse);
         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);
        // 执行BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
         currentRegistryProcessors.clear();
      }

      // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
     // 执行postProcessBeanFactory#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.classtruefalse);

   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
   List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
   List<String> orderedPostProcessorNames = new ArrayList<String>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
  // 进行分类,分别执行
   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<BeanFactoryPostProcessor>();
   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<BeanFactoryPostProcessor>();
   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();
}

registerBeanPostProcessors注册BeanPostProcessor

注册bean的后处理器,调用是在bean实例化阶段调用的

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


public static void registerBeanPostProcessors(
   ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)
 
{

  String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.classtruefalse);

  // 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 只是一个日志打印,如果spring的后处理器还没有开始注册就已经开始了bean初始化时,就会打印信息
  beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

  // Separate between BeanPostProcessors that implement PriorityOrdered,
  // Ordered, and the rest.
  // 分类  优先级的、有序的、无序的
  List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
  List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
  List<String> orderedPostProcessorNames = new ArrayList<String>();
  List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
  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);
   }
  }

  // First, register the BeanPostProcessors that implement PriorityOrdered.
  // 先注册所有实现了PriorityOrdered的BeanPostProcessors
  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

  // Next, register the BeanPostProcessors that implement Ordered.
  // 注册所有实现了Ordered的BeanPostProcessors
  List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
  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.
  // 注册所有无序的BeanPostProcessor
  List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
  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));
 }

initMessageSource初始化消息资源

提取配置中定义的MessageSource,进行国际化的配置

protected void initMessageSource() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  // MESSAGE_SOURCE_BEAN_NAME = "messageSource"
   if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { // 如果配置了messageSource
      this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
      // Make MessageSource aware of parent MessageSource.
      if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
         HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
         if (hms.getParentMessageSource() == null) {
            // Only set parent context as parent MessageSource if no parent MessageSource
            // registered already.
            hms.setParentMessageSource(getInternalParentMessageSource());
         }
      }
      
   }
   else { // 如果没有配置messageSource,会使用DelegatingMessageSource来作为messageSource
      // Use empty MessageSource to be able to accept getMessage calls.
      DelegatingMessageSource dms = new DelegatingMessageSource();
      dms.setParentMessageSource(getInternalParentMessageSource());
      this.messageSource = dms;
      beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
      
   }
}

initApplicationEventMulticaster事件广播

当出现事件时调用ApplicationEventMulticaster#multicastEvent调用invokeListener来执行监听器org.springframework.context.ApplicationListener#onApplicationEvent

protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  //APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster"
   if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { // 自定义事件广播
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      
   }
   else { // 没有自定义事件广播,使用默认的SimpleApplicationEventMulticaster
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      
   }
}

registerListeners注册监听器

protected void registerListeners() {
   // Register statically specified listeners first.
   for (ApplicationListener<?> listener : getApplicationListeners()) {
      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.classtruefalse);
   for (String listenerBeanName : listenerBeanNames) {
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
   }

   // Publish early application events now that we finally have a multicaster...
   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
   this.earlyApplicationEvents = null;
   if (earlyEventsToProcess != null) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
   }
}

finishBeanFactoryInitialization完成BeanFactory初始化

包括ConversionService的设置、非延迟加载的bean的初始化工作

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // Initialize conversion service for this context.
  // CONVERSION_SERVICE_BEAN_NAME = "conversionService"
  // ConversionService 自定义转换器
   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(new StringValueResolver() {
         @Override
         public String resolveStringValue(String strVal) {
            return getEnvironment().resolvePlaceholders(strVal);
         }
      });
   }

   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.classfalsefalse);
   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,不期待之后更改这些数据
   beanFactory.freezeConfiguration();

   // Instantiate all remaining (non-lazy-init) singletons.
  // 初始化剩下的非惰性的单例bean
   beanFactory.preInstantiateSingletons();
}
preInstantiateSingletons初始化bean

将bean进行实例化

public void preInstantiateSingletons() throws BeansException {
   

   // 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<String>(this.beanDefinitionNames);

   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {
     // 拿到bean的定义信息
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
     // 非抽象的、单例的、非懒加载的
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
        // 是否FactoryBean,FactoryBean是通过调用getObject来进行创建对象的
         if (isFactoryBean(beanName)) {
            final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
            boolean isEagerInit;
            
            isEagerInit = (factory instanceof SmartFactoryBean &&
                     ((SmartFactoryBean<?>) factory).isEagerInit());
            if (isEagerInit) {
               getBean(beanName);
            }
         }
         else {
           // getBean是实际创建bean实例的操作
            getBean(beanName);
         }
      }
   }

   // 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;
         smartSingleton.afterSingletonsInstantiated();
         
      }
   }
}
getBean创建bean实例
public Object getBean(String name) throws BeansException {
   return doGetBean(name, nullnullfalse);
}


protected <T> doGetBean(
   final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)

   throws BeansException 
{
  // 获取bean名称,主要是解决FactoryBean加的&前缀
  final String beanName = transformedBeanName(name);
  Object bean;

  // Eagerly check singleton cache for manually registered singletons.
  // 从缓存中获取
  Object sharedInstance = getSingleton(beanName);
  if (sharedInstance != null && args == null) {
  
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  }

  else {
   // Fail if we're already creating this bean instance:
   // We're assumably within a circular reference.
   if (isPrototypeCurrentlyInCreation(beanName)) {
    throw new BeanCurrentlyInCreationException(beanName);
   }

   // Check if bean definition exists in this factory.
   BeanFactory parentBeanFactory = getParentBeanFactory();
   if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    // Not found -> check parent.
    String nameToLookup = originalBeanName(name);
    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) {
    markBeanAsCreated(beanName);
   }

   try {
    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.
    if (mbd.isSingleton()) { // 单例
     sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
      @Override
      public Object getObject() throws BeansException {
       try {
        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 = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
    }

    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);
    }

    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, new ObjectFactory<Object>() {
       @Override
       public Object getObject() throws BeansException {
        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 && bean != null && !requiredType.isInstance(bean)) {
   try {
    return getTypeConverter().convertIfNecessary(bean, requiredType);
   }
   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)从缓存获取
public Object getSingleton(String beanName) {
   return getSingleton(beanName, true);
}


protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  // 从singletonObjects缓存中取
  // singletonObjects中存的是beanName和bean实例
  // singletonObjects是一级缓存
   Object singletonObject = this.singletonObjects.get(beanName);
  // 缓存中没有
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
     // 锁定全局变量进行处理
      synchronized (this.singletonObjects) {
        // 如果该bean正在进行加载则不进行处理,直接返回
        // earlySingletonObjects中存的是beanName和bean实例,但是与singletonObjects不同的是,存储的是还没进行属性注入操作的Bean的实例,,目的是为了监测循环引用
        // earlySingletonObjects是二级缓存
         singletonObject = this.earlySingletonObjects.get(beanName);
         if (singletonObject == null && allowEarlyReference) {
           // 从singletonFactories中获取,对于某些方法需要提前进行初始化时则会调用addSingletonFactory方法将对应的ObjectFactory初始化策略存在singletonFactories中
           // singletonFactories中存的是beanName和创建bean的ObjectFactory工厂
           // singletonFactories是三级缓存
            ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
            if (singletonFactory != null) {
              // 调用ObjectFactory的getObject方法
               singletonObject = singletonFactory.getObject();
              // 放入到二级缓存中
              // 记录在缓存earlySingletonObjects中,earlySingletonObjects和singletonFactories互斥,earlySingletonObjects与singletonObjects的不同之处在于当一个单例bean被放入该缓存后,那么其他的bean在创建过程中就能通过getBean方法获取到,目的是用来监测循环引用
               this.earlySingletonObjects.put(beanName, singletonObject);
               this.singletonFactories.remove(beanName);
            }
         }
      }
   }
   return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
getSingleton(String beanName, ObjectFactory<?> singletonFactory)创建bean
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
   synchronized (this.singletonObjects) {
      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!)");
         }
         
         beforeSingletonCreation(beanName);
         boolean newSingleton = false;
         boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
         if (recordSuppressedExceptions) {
            this.suppressedExceptions = new LinkedHashSet<Exception>();
         }
         try {
           // 这里调用的就是createBean方法
            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) {
            
            throw ex;
         }
         finally {
            if (recordSuppressedExceptions) {
               this.suppressedExceptions = null;
            }
            afterSingletonCreation(beanName);
         }
         if (newSingleton) {
            addSingleton(beanName, singletonObject);
         }
      }
      return (singletonObject != NULL_OBJECT ? singletonObject : null);
   }
}
createBean创建bean

调用的是org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean,其内实际调用的是doCreateBean

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      throws BeanCreationException 
{

   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
   if (instanceWrapper == null) {
     // 创建bean实例,但是未设置属性
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
   Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
   mbd.resolvedTargetType = beanType;

   // Allow post-processors to modify the merged bean definition.
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            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.
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      
      addSingletonFactory(beanName, new ObjectFactory<Object>() {
         @Override
         public Object getObject() throws BeansException {
            return getEarlyBeanReference(beanName, mbd, bean);
         }
      });
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
     // 填充属性,上边实例化的时候只是默认属性
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
        // 1.调用 xxAware方法,BeanPostProcessor的前置处理postProcessBeforeInitialization,init-method,BeanPostProcessor的后置处理postProcessAfterInitialization
         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<String>(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 " +
                     "'getBeanNamesForType' 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;
}

1.initializeBean

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
   // 调用 xxAware方法,
      invokeAwareMethods(beanName, bean);

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
     // BeanPostProcessor的前置处理postProcessBeforeInitialization,
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
     // init-method,
      invokeInitMethods(beanName, wrappedBean, mbd);
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
   }
   if (mbd == null || !mbd.isSynthetic()) {
     // BeanPostProcessor的后置处理postProcessAfterInitialization,AOP动态代理在此处
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }
   return wrappedBean;
}

finishRefresh完成

protected void finishRefresh() {
   // Initialize lifecycle processor for this context.
  // 初始化LifecycleProcessor
   initLifecycleProcessor();

   // Propagate refresh to lifecycle processor first.
  // 执行所有LifecycleProcessor的onRefresh方法
   getLifecycleProcessor().onRefresh();

   // Publish the final event.
  // 发布ContextRefreshedEvent事件
   publishEvent(new ContextRefreshedEvent(this));

   // Participate in LiveBeansView MBean, if active.
   LiveBeansView.registerApplicationContext(this);
}

本文由 mdnice 多平台发布


http://www.mrgr.cn/p/82862134

相关文章

k8s 资源组版本支持列表

1 kubernetes的资源注册表 kube-apiserver组件启动后的第一件事情是将Kubernetes所支持的资源注册到Scheme资源注册表中,这样后面启动的逻辑才能够从Scheme资源注册表中拿到资源信息并启动和运行API服务。 kube-apiserver资源注册分为两步:第1步,初始化Scheme资源注册表;…

ASP.NET视频点播系统的设计与实现

摘 要 本文阐述了基于WEB的交互式视频点播系统的协议原理、软件结构和设计实现。本视频点播系统根据流媒体传输原理&#xff0c;在校园局域网的基础上模拟基于Web的视频点播系统&#xff0c;实现用户信息管理、视频文件的添加、删除、修改及在线播放和搜索功能。本系统是一个…

linus下Anaconda创建虚拟环境pytorch

一、虚拟环境 1.创建 输入下面命令 conda create -n env_name python3.8 输入y 2.激活环境 输入 conda activate env_name 二、一些常用的命令 在Linux的控制平台 切换到当前的文件夹 cd /根目录/次目录 查看conda目录 conda list 查看pip目录 pip list查看历史命…

【YoloDeployCsharp】基于.NET Framework的YOLO深度学习模型部署测试平台

基于.NET Framework 4.8 开发的深度学习模型部署测试平台,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等应用场景,同时支持图像与视频检测。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runtime以及OpenCV DNN,支持CPU、IGP…

手撸Mybatis(三)——收敛SQL操作到SqlSession

本专栏的源码&#xff1a;https://gitee.com/dhi-chen-xiaoyang/yang-mybatis。 引言 在上一章中&#xff0c;我们实现了读取mapper配置并构造相关的mapper代理对象&#xff0c;读取mapper.xml文件中的sql信息等操作&#xff0c;现在&#xff0c;在上一章的基础上&#xff0c…

Content type ‘application/json;charset=UTF-8‘ not supported异常的解决过程

1.首先说明开发场景 *就是对该json格式数据传输到后台 后台实体类 import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.sp…

Stm32CubeMX 为 stm32mp135d 添加 adc

Stm32CubeMX 为 stm32mp135d 添加 adc 一、启用设备1. adc 设备添加2. adc 引脚配置2. adc 时钟配置 二、 生成代码1. optee 配置 adc 时钟和安全验证2. linux adc 设备 dts 配置 bringup 可参考&#xff1a; Stm32CubeMX 生成设备树 一、启用设备 1. adc 设备添加 启用adc设…

Linux---软硬链接

软链接 我们先学习一下怎样创建软链接文件&#xff0c;指令格式为&#xff1a;ln -s 被链接的文件 生成的链接文件名 我们可以这样记忆&#xff1a;ln是link的简称&#xff0c;s是soft的简称。 我们在下面的图片中就是给test文件生成了一个软链接mytest&#xff1a; 我们来解…

狂神spring学习笔记

1. Spring 1. 简介 一个融合器,一个简化开发的框架 spring官网 github地址 2. Maven坐标 <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency><groupId>org.springframework</groupId><artifactId>sp…

android studio拍照功能问题解决

1.点击拍照功能直接闪退 2.拍照后不能选择确认键&#xff0c;无法保存 上述是在android studio做项目中经常会使用到模拟器或真机的拍照功能时主要遇到的两个问题。 解决方法&#xff1a; 1.直接闪退问题&#xff1a; if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N)…

2024-05-04 如何为antd的table设置序号

给columns加多一列即可:const columns = [{title: "序号",key: "index",render: (_, record, index) => index + 1,},...]如图:

Multisim14--软件简介及安装教程(内含安装包)

安装包见文章末尾一、软件简介 Multisim是美国国家仪器(NI)有限公司推出的以Windows为基础的仿真工具,适用于板级的模拟/数字电路板的设计工作。它包含了电路原理图的图形输入、电路硬件描述语言输入方式,具有丰富的仿真分析能力。工程师们可以使用Multisim交互式地搭建电路…

开源版本管理系统的搭建一:SVN服务端安装

作者&#xff1a;私语茶馆 1.Windows搭建SVN版本管理系统 点评&#xff1a;SVN本身非常简洁易用&#xff0c;VisualSVN文档支撑非常好&#xff0c;客户端TortoiseSVN非常专业。5星好评。 1.1.SVN概要和组成 背景介绍 Svn是一个开源版本管理系统&#xff0c;由CollabNet公司…

随机抽奖

问题:随机抽奖公式 解决1:只一个抽奖结果=INDEX(A:A,RANDBETWEEN(2,11))解决2:多个抽奖结果且不能有重复=TAKE(SORTBY(A2:A11,RANDARRAY(10)),6)将抽奖名单按随机序排序,再提取前六个。

shpfile转GeoJSON;控制shp转GeoJSON的精度;如何获取GeoJSON;GeoJSON是什么有什么用;GeoJSON结构详解(带数据示例)

目录 一、GeoJSON是什么 二、GeoJSON的结构组成 2.1、点&#xff08;Point&#xff09;数据示例 2.2、线&#xff08;LineString&#xff09;数据示例 2.3、面&#xff08;Polygon&#xff09;数据示例 2.4、特征&#xff08;Feature&#xff09;数据示例 2.5、特征集合&…

2024-05-04 如何去掉uniapp的h5开发中url存在的#号?

如果你正在用uniapp开发h5页面,你会发现h5页面的url里带有一个#号,比如:http://localhost:8080/#/pages/index/index 原因:uniapp默认模式导致 解决方案:修改uniapp默认模式为history,如下图所示:

【Mac】mac 安装 prometheus 报错 prometheus: prometheus: cannot execute binary file

1、官网下载 Download | Prometheus 这里下载的是prometheus-2.51.2.linux-amd64.tar.gz 2、现象 解压之后启动Prometheus 启动脚本&#xff1a; nohup ./prometheus --config.fileprometheus.yml > prometheus.out 2>&1 & prometheus.out日志文件&#xff…

开箱子咸鱼之王H5游戏源码_内购修复优化_附带APK完美运营无bug最终版__GM总运营后台_附带安卓版本

内容目录 一、详细介绍二、效果展示2.效果图展示 三、学习资料下载 一、详细介绍 1.包括原生打包APK&#xff0c;资源全部APK本地化&#xff0c;基本上不跑服务器宽带 2.优化后端&#xff0c;基本上不再一直跑内存&#xff0c;不炸服响应快&#xff01; 3.优化前端&#xff0c…

Python自动化测试中JSON数据处理遇到的错误

在接口自动化测试领域,使用Excel管理测试数据是一种常见的做法。本文将分享一个实际案例,介绍在Python自动化测试框架中,如何从响应结果中提取所需数据,并探讨在处理JSON格式数据时遇到的一个典型问题及其解决方案。 首先,让我们了解测试数据的基本格式。在Excel中,我们定…

【云原生】Docker 实践(二):什么是 Docker 的镜像

【Docker 实践】系列共包含以下几篇文章&#xff1a; Docker 实践&#xff08;一&#xff09;&#xff1a;在 Docker 中部署第一个应用Docker 实践&#xff08;二&#xff09;&#xff1a;什么是 Docker 的镜像Docker 实践&#xff08;三&#xff09;&#xff1a;使用 Dockerf…