Spring IoC 学习

Spring IOC核心思想 图片引用自 Spring三十五问,四万字+五十图详解!
Spring IOC 核心思想

准备Spring Debug环境
在学习源码之前,需要准备一下环境。
下面是用到的环境信息:

  1. spring使用5.1.8
  2. 使用spring_bean_test.xml配置文件
  3. 创建一个测试类,使用 ClassPathXmlApplicationContext 去debug
  4. 准备一个类去查看spring的一些功能,这里用Preson
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>

spring_bean_test.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="personBean" name="personBean_1,persionBean_2" class="com.wkq.java.spring.demo.model.Person"
          init-method="initPerson"
          destroy-method="destroyPerson">
        <property name="id" value="1"/>
        <property name="name" value="johnny"/>
        <property name="age" value="10"/>
    </bean>

</beans>

debug方法

import com.wkq.java.spring.demo.model.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author weikeqin
 */
public class SpringBeanTest {
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring_bean_test.xml");
        Person person = applicationContext.getBean(Person.class);
        System.out.println("print get bean = " + person);
        applicationContext.destroy();
    }

}
package com.wkq.java.spring.demo.model;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author weikeqin
 */
public class Person implements InitializingBean, DisposableBean, BeanNameAware, BeanFactoryAware, ApplicationContextAware {

    private Integer id;
    private String name;
    private Integer age;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    public void initPerson() {
        System.out.println("custom init method of person bean is invoked!");
    }

    public void destroyPerson() {
        System.out.println("custom Destroy method of person bean is invoked!");
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("setBeanFactory method of person is invoked");
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("setBeanName method of person is invoked");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean Destroy method of person bean is invoked!");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet method of person bean is invoked!");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }
}

(0) Spring IoC 源码解读

 源码使用spring 5.1.8版本

主要讲refresh()的部分
refresh()的代码包含了 Bean定义解析、Bean初始化、Bean依赖注入 等

1、Bean解析、注册 (从xml或者注解等)
2、Bean初始化 (用到了反射加载类信息)
3、Bean依赖注入 (用到了反射)

源码入口

源码位置: org.springframework.context.support.AbstractApplicationContext

@Override
public void refresh() throws BeansException, IllegalStateException {

  // 避免并发问题   refresh()还没结束,又启动或销毁容器
  synchronized (this.startupShutdownMonitor) {

    // 1、准备工作,记录下容器的启动时间、标记“已启动”状态、处理配置文件中的占位符
    // Prepare this context for refreshing.
    prepareRefresh();

    // 2、重要  初始化BeanFactory,并进行配置读取解析(本次是XML文件读取)、bean注册 
    // 配置读取解析完后就会解析成一个个BeanDefinition对象,保存到 beanDefinitionMap,还有aliasMap、beanDefinitionNames等
    // 这里说的 Bean 还没有初始化,只是配置信息都提取出来了
    // Tell the subclass to refresh the internal bean factory.
    ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

    // 3、 对BeanFactory进行各种功能填充。
    // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
    // Prepare the bean factory for use in this context.
    prepareBeanFactory(beanFactory);

    try {
      // 4、对 BeanFactory 做额外处理。 默认没有实现 
      // Bean 如果实现了BeanFactoryPostProcessor,在容器初始化以后,Spring会负责调用里面的 postProcessBeanFactory方法
      // 提供给子类的扩展点,到这里的时候,所有的 Bean 都加载、注册完成了,但是都还没有初始化具体的子类可以在这步的时候添加一些特殊的 BeanFactoryPostProcessor 的实现类或做点什么事
      // Allows post-processing of the bean factory in context subclasses.
      postProcessBeanFactory(beanFactory);

      // 5、激活各种BeanFactory 处理器(调用了各种BeanFactoryPostProcessor)。
      // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法 
      // 比如 ConfigurationClassPostProcessor,用来处理@ComponentScan和@Component注解,扫描并把bean的配置信息注册到beanDefinitionMap 。
      // Invoke factory processors registered as beans in the context.
      invokeBeanFactoryPostProcessors(beanFactory);

      // 6、注册和创建拦截bean创建的bean处理器。
      // 注册 BeanPostProcessor 的实现类 
      // 比如 AutowiredAnnotationBeanPostProcessor 处理器,用来处理@Autowirte注解 
      // 注意,到这里 BeanPostProcessor 在这一步已经完成了创建。Bean还没初始化
      // Register bean processors that intercept bean creation.
      registerBeanPostProcessors(beanFactory);

      // 7、为上下文初始化Message源,对不同语言的消息体进行国际化处理
      // Initialize message source for this context.
      initMessageSource();

      
      // 8、初始化当前 ApplicationContext 的事件广播器
      // Initialize event multicaster for this context.
      initApplicationEventMulticaster();


      // 9、留给子类来初始化其他bean 
      // 典型的模板方法(钩子方法),子类可以在这里初始化一些特殊的 Bean(在初始化 singleton beans 之前)
      // Initialize other special beans in specific context subclasses.
      onRefresh();

      // 10、在所有注册的bean中查找listener bean,注册到消息广播器中 
      // 注册事件监听器,监听器需要实现 ApplicationListener 接口。
      // Check for listener beans and register them.
      registerListeners();

      // 11、 重点  初始化剩余的 singleton beans (lazy-init 的除外)
      // Instantiate all remaining (non-lazy-init) singletons.
      finishBeanFactoryInitialization(beanFactory);
      
      // 12、广播事件,ApplicationContext 初始化完成
      // 完成刷新过程,通知生命周期处理器 lifecycleProcesseor 刷新过程,同时发出ContextRefreshEvent 通知
      // Last step: publish corresponding event.
      finishRefresh();
    }

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

      // 销毁已经初始化的 singleton 的 Beans,以免有些 bean 会一直占用资源
      // Destroy already created singletons to avoid dangling resources.
      destroyBeans();

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

      // Propagate exception to caller.
      throw ex;
    }

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

refesh()流程中,共有12步,但是并不是每一步都那么重要需要注意的几个点:
1、prepareRefresh() 创建容器前的准备工作
2、obtainFreshBeanFactory() 创建 BeanFactory
3、prepareBeanFactory(beanFactory) 对BeanFactory进行一些特征的设置工作
11、finishBeanFactoryInitialization(beanFactory); 初始化所有的 singleton beans(DI的入口)

(1) prepareRefresh()

/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {

    // 记录启动时间,
    // 将 active 属性设置为 true,closed 属性设置为 false,它们都是 AtomicBoolean 类型
    // Switch to active.
    this.startupDate = System.currentTimeMillis();
    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();

    // Store pre-refresh ApplicationListeners...
    if (this.earlyApplicationListeners == null) {
        this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    }
    else {
        // Reset local application listeners to pre-refresh state.
        this.applicationListeners.clear();
        this.applicationListeners.addAll(this.earlyApplicationListeners);
    }

    // Allow for the collection of early ApplicationEvents,
    // to be published once the multicaster is available...
    this.earlyApplicationEvents = new LinkedHashSet<>();
}

(2) 重点 obtainFreshBeanFactory()

创建Bean容器,加载并注册Bean (IoC初始化里面最重要的部分)

obtainFreshBeanFactory()的主要逻辑如下

初始化BeanFactory
加载Bean
注册Bean

注意:这步完成后,只完成了xml文件解析,并把bean名称注册到,并没有完成初始化,实际的实例并没有被创建。

源码位置: AbstractApplicationContext::obtainFreshBeanFactory()

/**
  * Tell the subclass to refresh the internal bean factory.
  * @return the fresh BeanFactory instance
  * @see #refreshBeanFactory()
  * @see #getBeanFactory()
  */
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  // 关闭旧的 BeanFactory (如果有),创建新的 BeanFactory,加载 Bean 定义、注册 Bean 等等
  refreshBeanFactory();
  // 返回上一步刚刚创建的BeanFactory
  return getBeanFactory();
}

(2.1) 创建BeanFactory

源码位置: AbstractRefreshableApplicationContext::refreshBeanFactory()

/**
  * This implementation performs an actual refresh of this context's underlying
  * bean factory, shutting down the previous bean factory (if any) and
  * initializing a fresh bean factory for the next phase of the context's lifecycle.
  */
@Override
protected final void refreshBeanFactory() throws BeansException {
   // 如果 ApplicationContext 已经加载过 BeanFactory,销毁所有的Bean,关闭BeanFactory
   // 注意点:应用中BeanFactory是可以有多个的,这里可不是说全局是否有BeanFactory,而是说当前的ApplicationContext有没有BeanFactory!
  if (hasBeanFactory()) {
    destroyBeans();
    closeBeanFactory();
  }
  try {
    // 初始化一个 DefaultListableBeanFactory
    DefaultListableBeanFactory beanFactory = createBeanFactory();
    beanFactory.setSerializationId(getId());
    // 设置BeanFactory属性   比如: 是否允许Bean覆盖、是否允许循环引用 
    customizeBeanFactory(beanFactory);
    // 重要 加载BeanDefinition到BeanFactory  这块把,在加载Class的时候用到了反射
    loadBeanDefinitions(beanFactory);
    synchronized (this.beanFactoryMonitor) {
      this.beanFactory = beanFactory;
    }
  }
  catch (IOException ex) {
    throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  }
}

看到这里的时候,思考一下 DefaultListableBeanFactory 的作用
思考一下 AbstractRefreshableApplicationContext 的作用

AbstractRefreshableApplicationContext 继承 AbstractApplicationContext
AbstractApplicationContext 继承DefaultResourceLoader 实现了ConfigurableApplicationContext接口
ConfigurableApplicationContext 接口 继承了 ApplicationContext
ApplicationContext 继承自 BeanFactory,但同时 ApplicationContext 还继承了其它接口。
AbstractRefreshableApplicationContext 其实功能强大,实现了 资源加载 以及 资源缓存 等
以后所有的 BeanFactory 相关的操作其实是委托给这个实例来处理的。

(重要) 把bean定义注册到bean工厂 loadBeanDefinitions(beanFactory)

loadBeanDefinitions
 
源码位置 AbstractRefreshableApplicationContext::loadBeanDefinitions

/**
  * Load bean definitions into the given bean factory, typically through
  * delegating to one or more bean definition readers.
  * @param beanFactory the bean factory to load bean definitions into
  * @throws BeansException if parsing of the bean definitions failed
  * @throws IOException if loading of bean definition files failed
  * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader
  * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
  */
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
    throws BeansException, IOException;

AbstractXmlApplicationContext::loadBeanDefinitions

/**
  * Loads the bean definitions via an XmlBeanDefinitionReader.
  * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
  * @see #initBeanDefinitionReader
  * @see #loadBeanDefinitions
  */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {

  // beanDefinitionReader 获取到 beanFactory 的引用,这个引用会在beanDefinition被加载完毕要注册的时候使用到。
  // Create a new XmlBeanDefinitionReader for the given BeanFactory.
  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);
  // 用beanDefinitionReader去加载xml内容
  loadBeanDefinitions(beanDefinitionReader);
}


/**
  * Load the bean definitions with the given XmlBeanDefinitionReader.
  * <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory}
  * method; hence this method is just supposed to load and/or register bean definitions.
  * @param reader the XmlBeanDefinitionReader to use
  * @throws BeansException in case of bean registration errors
  * @throws IOException if the required XML document isn't found
  * @see #refreshBeanFactory
  * @see #getConfigLocations
  * @see #getResources
  * @see #getResourcePatternResolver
  */
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
  Resource[] configResources = getConfigResources();
  if (configResources != null) {
    reader.loadBeanDefinitions(configResources);
  }
  String[] configLocations = getConfigLocations();
  if (configLocations != null) {
    // 通过路径名去获取Resource  就是用到的xml文件 spring_bean_test.xml 
    reader.loadBeanDefinitions(configLocations);
  }
}

源码位置: AbstractBeanDefinitionReader::loadBeanDefinitions

@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
  Assert.notNull(locations, "Location array must not be null");
  int count = 0;
  for (String location : locations) {
    count += loadBeanDefinitions(location);
  }
  return count;
}

@Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
  return loadBeanDefinitions(location, null);
}

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 {
      // location在这儿是 spring_bean_test.xml
      Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
      // 在这儿根据xml加载bean
      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;
  }
}

@Override
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
  Assert.notNull(resources, "Resource array must not be null");
  int count = 0;
  for (Resource resource : resources) {
    count += loadBeanDefinitions(resource);
  }
  return count;
}

 源码位置: XmlBeanDefinitionReader::loadBeanDefinitions

@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
  return loadBeanDefinitions(new EncodedResource(resource));
}


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 == null) {
    currentResources = new HashSet<>(4);
    this.resourcesCurrentlyBeingLoaded.set(currentResources);
  }
  if (!currentResources.add(encodedResource)) {
    throw new BeanDefinitionStoreException(
        "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
  }
  try {
    InputStream inputStream = encodedResource.getResource().getInputStream();
    try {
      InputSource inputSource = new InputSource(inputStream);
      if (encodedResource.getEncoding() != null) {
        inputSource.setEncoding(encodedResource.getEncoding());
      }
      // 处理加载bean的逻辑
      return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
    }
    finally {
      inputStream.close();
    }
  }
  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::doLoadBeanDefinitions

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
    throws BeanDefinitionStoreException {

  try {
    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);
  }
}
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
  BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
  int countBefore = getRegistry().getBeanDefinitionCount();
  // 注册bean
  documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
  return getRegistry().getBeanDefinitionCount() - countBefore;
}

源码位置: DefaultBeanDefinitionDocumentReader::registerBeanDefinitions

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
  this.readerContext = readerContext;
  doRegisterBeanDefinitions(doc.getDocumentElement());
}


protected void doRegisterBeanDefinitions(Element root) {
  // Any nested <beans> elements will cause recursion in this method. In
  // order to propagate and preserve <beans> default-* attributes correctly,
  // keep track of the current (parent) delegate, which may be null. Create
  // the new (child) delegate with a reference to the parent for fallback purposes,
  // then ultimately reset this.delegate back to its original (parent) reference.
  // this behavior emulates a stack of delegates without actually necessitating one.
  BeanDefinitionParserDelegate parent = this.delegate;
  this.delegate = createDelegate(getReaderContext(), root, parent);

  if (this.delegate.isDefaultNamespace(root)) {
    String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
    if (StringUtils.hasText(profileSpec)) {
      String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
          profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
      // We cannot use Profiles.of(...) since profile expressions are not supported
      // in XML config. See SPR-12458 for details.
      if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
        if (logger.isDebugEnabled()) {
          logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
              "] not matching: " + getReaderContext().getResource());
        }
        return;
      }
    }
  }

  preProcessXml(root);
  // 解析BeanDefinition
  parseBeanDefinitions(root, this.delegate);
  postProcessXml(root);

  this.delegate = parent;
}



protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
  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;
        if (delegate.isDefaultNamespace(ele)) {
          // 解析
          parseDefaultElement(ele, delegate);
        }
        else {
          delegate.parseCustomElement(ele);
        }
      }
    }
  }
  else {
    delegate.parseCustomElement(root);
  }
}
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 /> 标签
    // 处理BeanDefinition
    processBeanDefinition(ele, delegate);
  }
  else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
    // 嵌套的 <beans /> 标签,需要递归
    // recurse
    doRegisterBeanDefinitions(ele);
  }
}
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
  // 将 <bean /> 节点中的信息提取出来,然后封装到一个 BeanDefinitionHolder 中 
  BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
  if (bdHolder != null) {
    bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
    try {
      // 注册最终的装饰实例。  仅仅是注册,没有实例化 
      // Register the final decorated instance.
      BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
    }
    catch (BeanDefinitionStoreException ex) {
      getReaderContext().error("Failed to register bean definition with name '" +
          bdHolder.getBeanName() + "'", ele, ex);
    }
    // Send registration event.
    getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
  }
}
// 解析
public AbstractBeanDefinition parseBeanDefinitionElement(
    Element ele, String beanName, @Nullable BeanDefinition containingBean) {

  this.parseState.push(new BeanEntry(beanName));

  String className = null;
  if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
    className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
  }
  String parent = null;
  if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
    parent = ele.getAttribute(PARENT_ATTRIBUTE);
  }

  try {
    // 设置类信息
    AbstractBeanDefinition bd = createBeanDefinition(className, parent);

    parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
    bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));

    // 解析 <meta />
    parseMetaElements(ele, bd);
    // 解析 <lookup-method />
    parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
    // 解析 <replaced-method />
    parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

    // 解析 <constructor-arg />
    parseConstructorArgElements(ele, bd);
    // 解析 <property />
    parsePropertyElements(ele, bd);
    // 解析 <qualifier />
    parseQualifierElements(ele, bd);

    bd.setResource(this.readerContext.getResource());
    bd.setSource(extractSource(ele));

    return bd;
  }
  catch (ClassNotFoundException ex) {
    error("Bean class [" + className + "] not found", ele, ex);
  }
  catch (NoClassDefFoundError err) {
    error("Class that bean class [" + className + "] depends on not found", ele, err);
  }
  catch (Throwable ex) {
    error("Unexpected failure during bean definition parsing", ele, ex);
  }
  finally {
    this.parseState.pop();
  }

  return null;
}

注册bean registerBeanDefinition

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

  // 注册bean主名称。 对应xml文件 bean标签下 id="personBean" 
  // Register bean definition under primary name.
  String beanName = definitionHolder.getBeanName();
  registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

  // 注册别名  对应xml文件 bean标签下 name="personBean_1,persionBean_2"  注册personBean_1,persionBean_2两个别名
  // Register aliases for bean name, if any.
  String[] aliases = definitionHolder.getAliases();
  if (aliases != null) {
    for (String alias : aliases) {
      registry.registerAlias(beanName, alias);
    }
  }
}

() 注册BeanDefinition

源码位置: DefaultListableBeanFactory::registerBeanDefinition

@Override
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) beanDefinition).validate();
    }
    catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
          "Validation of bean definition failed", ex);
    }
  }

  // 检查 beanName(personBean) 是否已注册 
  BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
  if (existingDefinition != null) { // 处理重复名称的 Bean 定义的情况
    if (!isAllowBeanDefinitionOverriding()) {
      // // 如果不允许覆盖的话,抛异常
      throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
    }
    else if (existingDefinition.getRole() < beanDefinition.getRole()) {
      // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
      if (logger.isInfoEnabled()) {
        // 打印日志 用框架定义的Bean覆盖用户自定义的Bean 
        logger.info("Overriding user-defined bean definition for bean '" + beanName +
            "' with a framework-generated bean definition: replacing [" +
            existingDefinition + "] with [" + beanDefinition + "]");
      }
    }
    else if (!beanDefinition.equals(existingDefinition)) {
      if (logger.isDebugEnabled()) {
        // 
        logger.debug("Overriding bean definition for bean '" + beanName +
            "' with a different definition: replacing [" + existingDefinition +
            "] with [" + beanDefinition + "]");
      }
    }
    else {
      if (logger.isTraceEnabled()) {
        logger.trace("Overriding bean definition for bean '" + beanName +
            "' with an equivalent definition: replacing [" + existingDefinition +
            "] with [" + beanDefinition + "]");
      }
    }
    this.beanDefinitionMap.put(beanName, beanDefinition);
  }
  else {
    // 校验BeanCreate是否启动
    if (hasBeanCreationStarted()) {
      // Cannot modify startup-time collection elements anymore (for stable iteration)
      synchronized (this.beanDefinitionMap) {
        this.beanDefinitionMap.put(beanName, beanDefinition);
        List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
        updatedDefinitions.addAll(this.beanDefinitionNames);
        updatedDefinitions.add(beanName);
        this.beanDefinitionNames = updatedDefinitions;
        removeManualSingletonName(beanName);
      }
    }
    else {
      // Still in startup registration phase
      // 把bean放入map  key是bean的名称(对应xml文件bean标签id="personBean")  value是这个bean的定义 
      // beanDefinition里的内容  Generic bean: class [com.wkq.java.spring.demo.model.Person]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=initPerson; destroyMethodName=destroyPerson; defined in class path resource [spring_bean_test.xml]
      this.beanDefinitionMap.put(beanName, beanDefinition);
      this.beanDefinitionNames.add(beanName);
      removeManualSingletonName(beanName);
    }
    this.frozenBeanDefinitionNames = null;
  }

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

 到这儿为止,就把xml文件里的bean标签解析并且存储到 beanDefinitionMap 里了

 key=personBean 
 value=BeanDefinition对象  例子: Generic bean: class [com.wkq.java.spring.demo.model.Person]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=initPerson; destroyMethodName=destroyPerson; defined in class path resource [spring_bean_test.xml]
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);

完成了上面的三步后,目前ApplicationContext中有两种类型的结构,一个是DefaultListableBeanFactory,它是Spring IOC容器,另一种是若干个BeanDefinitionHolder,这里面包含实际的Bean对象 AbstractBeanDefition

需要把二者关联起来,这样Spring才能对Bean进行管理。在DefaultListableBeanFactory中定义了一个Map对象 beanDefinitionMap ,保存所有的BeanDefition。这个注册的过程就是把前面解析得到的Bean放入这个Map的过程。


(3) prepareBeanFactory(beanFactory)

prepareBeanFactory(beanFactory)

负责对BeanFactory进行一些特征的设置工作

/**
  * Configure the factory's standard context characteristics,
  * such as the context's ClassLoader and post-processors.
  * @param beanFactory the BeanFactory to configure
  */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  // 设置当前ApplicationContext的类加载器   BeanFactory需要加载类,所以需要获得类加载器
  // Tell the internal bean factory to use the context's class loader etc.
  beanFactory.setBeanClassLoader(getClassLoader());
  beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

  // Configure the bean factory with context callbacks.
  // 添加一个ApplicationContextAwareProcessor,主要针对实现了Aware接口的Bean 
  // 在Spring中我们自己的bean可以通过实现EnvironmentAware等一系列Aware接口,获取到Spring内部的一些对象。
  beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  // 依赖解析忽略, 设置哪些接口在进行依赖注入的时候应该被忽略
  // 通俗来说,下面几行的意思就是,如果某个 bean 依赖于以下几个接口的实现类,在自动装配的时候忽略它们,
  // Spring 会通过其他方式来处理这些依赖。
  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 赋值,如果有 bean 依赖了以下几个,会注入这边相应的值
  // 当前的beanFactory变量其实是DefaultListableBeanFactory  但是DefaultListableBeanFactory不仅仅有beanFactory的作用 还有BeanRegistry的作用 
  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.
  // 这个postProcessor的作用就是在bean实例化后,将ApplicationListener子类添加到 listener列表中, 可以理解成:注册事件监听器
  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()));
  }

  // Spring会默认注册一些有用的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());
  }
}

 

(11) 重点 finishBeanFactoryInitialization(beanFactory) 实例化所有单例

Spring会在这个阶段完成除懒加载的剩余的singleton beans 的实例化。
为什么这儿是剩余的singleton beans的实例化呢,因为Spring有一些内置的Bean在前面已经初始化了,所以这儿是剩余的bean的初始化。

/**
  * Finish the initialization of this context's bean factory,
  * initializing all remaining singleton beans.
  */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  // Initialize conversion service for this context.
  if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
      beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
    // 初始化的动作包装在 beanFactory.getBean() 中
    beanFactory.setConversionService(
        beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  }

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

  // 初始化 LoadTimeWeaverAware 类型的 Bean
  // 是 AspectJ 相关的内容
  // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  for (String weaverAwareName : weaverAwareNames) {
    getBean(weaverAwareName);
  }

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

  // 冻结所有BeanDefinition的元数据  到这一步,Spring已经开始预初始化 singleton beans,不希望这个时候还出现 bean 定义解析、加载、注册。
  // Allow for caching all bean definition metadata, not expecting further changes.
  beanFactory.freezeConfiguration();

  // 重点 最重要的部分   
  // 实例化所有剩余的(非懒加载的)单例bean。
  // 方法命名是 预实例化单例 
  // Instantiate all remaining (non-lazy-init) singletons.
  beanFactory.preInstantiateSingletons();
}

源码位置: DefaultListableBeanFactory::preInstantiateSingletons()

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

  // 复制一个包含所有BeanName的集合副本 this.beanDefinitionNames是在前面注册的
  // 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);

  // 触发所有非懒加载的singleton beans的初始化
  // Trigger initialization of all non-lazy singleton beans...
  for (String beanName : beanNames) {
    // Bean 可能有继承parent的关系,获取合并后的RootBeanDefinition
    RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    // 这儿会判断是否是 非抽象、single的、非懒加载的 
    if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      // 通过FactoryBean创建Bean
      if (isFactoryBean(beanName)) {
        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 {
        // 重点   除factoryBean正常Bean都会用这个逻辑, 进行Bean初始化
        getBean(beanName);
      }
    }
  }

  // 前面流程走完,说明所有的非懒加载singletonBean 完成了初始化
  // Trigger post-initialization callback for all applicable beans...
  for (String beanName : beanNames) {
    Object singletonInstance = getSingleton(beanName);
    // 如果定义的bean实现了SmartInitializingSingleton接口, 在这里会被回调
    if (singletonInstance instanceof SmartInitializingSingleton) {
      final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
      if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
          smartSingleton.afterSingletonsInstantiated();
          return null;
        }, getAccessControlContext());
      }
      else {
        smartSingleton.afterSingletonsInstantiated();
      }
    }
  }
}

getBean

源码位置: org.springframework.beans.factory.support.AbstractBeanFactory

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

/**
    * Return an instance, which may be shared or independent, of the specified bean.
    * @param name the name of the bean to retrieve
    * @param requiredType the required type of the bean to retrieve
    * @param args arguments to use when creating a bean instance using explicit arguments
    * (only applied when creating a new instance as opposed to retrieving an existing one)
    * @param typeCheckOnly whether the instance is obtained for a type check,
    * not for actual use
    * @return an instance of the bean
    * @throws BeansException if the bean could not be created
    */
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
        @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

    // 
    final String beanName = transformedBeanName(name);
    Object bean;

    // 检查beanName对应的实例是否已初始化
    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isTraceEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                        "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        // 如果是普通Bean的话,直接返回sharedInstance,如果是 FactoryBean 的话,返回它创建的那个实例对象
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        // 检查当前线程是否在创建prototype bean 
        // 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 (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 if (requiredType != null) {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
            else {
                return (T) parentBeanFactory.getBean(nameToLookup);
            }
        }

        if (!typeCheckOnly) {
            // 标记beanName对应的bean正在创建 
            markBeanAsCreated(beanName);
        }

        try {
            // 获取bean定义
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);

            // Guarantee initialization of beans that the current bean depends on.
            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 + "'");
                    }
                    // 注册依赖Bean
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // 创建bean实例
            // Create bean instance.
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, () -> {
                    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, () -> {
                        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.isTraceEnabled()) {
                logger.trace("Failed to convert bean '" + name + "' to required type '" +
                        ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

获取规范的bean名称

/**
  * Return the bean name, stripping out the factory dereference prefix if necessary,
  * and resolving aliases to canonical names.
  * @param name the user-specified name
  * @return the transformed bean name
  */
protected String transformedBeanName(String name) {
  return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
/**
  * 确定原始名称,将别名解析为规范名称。  有别名的时候把别名解析成规范的beanName
  * Determine the raw name, resolving aliases to canonical names.
  * @param name the user-specified name
  * @return the transformed name
  */
public String canonicalName(String name) {
  String canonicalName = name;
  // Handle aliasing...
  String resolvedName;
  do {
    // 根据别名拿到规范的bean名称  
    // 有可能别名引用别名所以要循环,直到拿不到resolvedName为空,没有别名为止
    resolvedName = this.aliasMap.get(canonicalName);
    if (resolvedName != null) {
      canonicalName = resolvedName;
    }
  }
  while (resolvedName != null);
  return canonicalName;
}

获取singleton Bean

 这块注意一下bean循环依赖

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

// 一级缓存 单例对象缓存:key=bean名称 value=bean实例  bean实例已完成初始化
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

// 二级缓存  早期单例对象的缓存:key=bean名称 value=bean实例  bean实例未完成初始化
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

// 三级缓存  单例工厂的缓存:key=bean名称  value=对象工厂  
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);


/**
  * 返回在给定名称下注册的(原始)单例对象。
  * 检查已经实例化的单例,也允许早期引用当前创建的单例(解决循环引用)。
  * 
  * Return the (raw) singleton object registered under the given name.
  * <p>Checks already instantiated singletons and also allows for an early
  * reference to a currently created singleton (resolving a circular reference).
  * @param beanName the name of the bean to look for
  * @param allowEarlyReference whether early references should be created or not
  * @return the registered singleton object, or {@code null} if none found
  */
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  // 首先从已注册的bean实例获取
  Object singletonObject = this.singletonObjects.get(beanName);
  // beanName对应的初始化实例为空 并且 beanName对应的实例正在创建
  if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
    synchronized (this.singletonObjects) {
      // 从未初始化完成的bean实例缓存中获取
      singletonObject = this.earlySingletonObjects.get(beanName);
      if (singletonObject == null && allowEarlyReference) {
        // 从singletonFactories中获取
        ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
        if (singletonFactory != null) {
          singletonObject = singletonFactory.getObject();
          this.earlySingletonObjects.put(beanName, singletonObject);
          this.singletonFactories.remove(beanName);
        }
      }
    }
  }
  return singletonObject;
}
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation =
    Collections.newSetFromMap(new ConcurrentHashMap<>(16));

/**
  * Return whether the specified singleton bean is currently in creation
  * (within the entire factory).
  * @param beanName the name of the bean
  */
public boolean isSingletonCurrentlyInCreation(String beanName) {
  return this.singletonsCurrentlyInCreation.contains(beanName);
}

创建Bean createBean

源码位置: AbstractAutowireCapableBeanFactory::createBean()

/**
    * 此类的中心方法:创建 bean 实例、填充 bean 实例、应用后处理器等。
    * 
    * Central method of this class: creates a bean instance,
    * populates the bean instance, applies post-processors, etc.
    * @see #doCreateBean
    */
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {

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

    // 把Bean对应的Class加载到JVM里
    // 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 {
        // 让 BeanPostProcessors 有机会返回一个代理而不是目标 bean 实例。
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        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.isTraceEnabled()) {
            logger.trace("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);
    }
}

解析BeanClass BeanClass()

 看代码,全限定类名是需要处理的,主要为了解决基本类型、数组类型、内部类等全限定类名里有特殊符号的问题。

源码位置: AbstractBeanDefinition::resolveBeanClass()

@Nullable
public Class<?> resolveBeanClass(@Nullable ClassLoader classLoader) throws ClassNotFoundException {
  // 获取类名
  String className = getBeanClassName();
  if (className == null) {
    return null;
  }
  // 把类加载到JVM
  Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
  this.beanClass = resolvedClass;
  return resolvedClass;
}

 Spring加载Bean对应的类

/**
    * 替换Class.forName()返回的基本类型实例(例如“int”)和数组类实例(例如“String[]”)。
    * 
    * Replacement for {@code Class.forName()} that also returns Class instances
    * for primitives (e.g. "int") and array class names (e.g. "String[]").
    * Furthermore, it is also capable of resolving inner class names in Java source
    * style (e.g. "java.lang.Thread.State" instead of "java.lang.Thread$State").
    * @param name the name of the Class
    * @param classLoader the class loader to use
    * (may be {@code null}, which indicates the default class loader)
    * @return a class instance for the supplied name
    * @throws ClassNotFoundException if the class was not found
    * @throws LinkageError if the class file could not be loaded
    * @see Class#forName(String, boolean, ClassLoader)
    */
public static Class<?> forName(String name, @Nullable ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {

    Assert.notNull(name, "Name must not be null");

    // 解析类名
    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        // 从缓存获取
        clazz = commonClassCache.get(name);
    }
    if (clazz != null) {
        return clazz;
    }

    // 如果name是以“[]”结尾的 
    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        // 获取基础元素类名  去掉数组
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // 以“[L”开始并且以“;”结尾
    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        // 获取基础元素类名 
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // 以"["开始的
    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        // 通过反射加载类  但是不实例化 initialize=false 
        return Class.forName(name, false, clToUse);
    }
    catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
        if (lastDotIndex != -1) {
            // 去掉内部类类名里的"$"
            String innerClassName =
                    name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR + name.substring(lastDotIndex + 1);
            try {
                // 加载内部类
                return Class.forName(innerClassName, false, clToUse);
            }
            catch (ClassNotFoundException ex2) {
                // Swallow - let original exception get through
            }
        }
        throw ex;
    }
}

resolveBeforeInstantiation()

/**
  * 应用实例化前后处理器,解析指定 bean 是否存在实例化前快捷方式。
  *
  * Apply before-instantiation post-processors, resolving whether there is a
  * before-instantiation shortcut for the specified bean.
  * @param beanName the name of the bean
  * @param mbd the bean definition for the bean
  * @return the shortcut-determined bean instance, or {@code null} if none
  */
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
  Object bean = null;
  if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
    // 确保此时实际解析了 bean 类。
    // Make sure bean class is actually resolved at this point.
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      Class<?> targetType = determineTargetType(beanName, mbd);
      if (targetType != null) {
        bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
        if (bean != null) {
          bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        }
      }
    }
    mbd.beforeInstantiationResolved = (bean != null);
  }
  return bean;
}

 
源码位置: AbstractAutowireCapableBeanFactory

/**
    * 实际创建指定的bean。 此时已经进行了预创建处理,例如 检查 postProcessBeforeInstantiation 回调。 区分默认 bean 实例化、使用工厂方法和自动装配构造函数。
    * 
    * Actually create the specified bean. Pre-creation processing has already happened
    * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
    * <p>Differentiates between default bean instantiation, use of a
    * factory method, and autowiring a constructor.
    * @param beanName the name of the bean
    * @param mbd the merged bean definition for the bean
    * @param args explicit arguments to use for constructor or factory method invocation
    * @return a new instance of the bean
    * @throws BeanCreationException if the bean could not be created
    * @see #instantiateBean
    * @see #instantiateUsingFactoryMethod
    * @see #autowireConstructor
    */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable 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.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // 允许后处理器修改合并的bean定义
    // 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;
        }
    }

    // 缓存单例以便能够解析循环引用
    // 即使由生命周期接口(如 BeanFactoryAware)触发。
    // 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) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                    "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // 填充Bean
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        }
        else {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }

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

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

    return exposedObject;
}

(2.4.3) 创建Bean实例

/**
    * Create a new instance for the specified bean, using an appropriate instantiation strategy:
    * factory method, constructor autowiring, or simple instantiation.
    * @param beanName the name of the bean
    * @param mbd the bean definition for the bean
    * @param args explicit arguments to use for constructor or factory method invocation
    * @return a BeanWrapper for the new instance
    * @see #obtainFromSupplier
    * @see #instantiateUsingFactoryMethod
    * @see #autowireConstructor
    * @see #instantiateBean
    */
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // 确保已经加载了对应的Class
    // Make sure bean class is actually resolved at this point.
    Class<?> beanClass = resolveBeanClass(mbd, beanName);

    // beanClass不为null、public权限 并且 可访问
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }

    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        // 采用工厂方法模式实例化
        return obtainFromSupplier(instanceSupplier, beanName);
    }

    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // 如果不是第一次创建,比如第二次创建 prototype bean。这种情况下,我们可以从第一次创建知道,采用无参构造函数,还是构造函数依赖注入 来完成实例化
    // Shortcut when re-creating the same bean...
    boolean resolved = false;
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            // 构造函数依赖注入
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            // 无参构造函数
            return instantiateBean(beanName, mbd);
        }
    }

    // Candidate constructors for autowiring?
    // 从 BeanPostProcessors 确定构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        // 构造函数依赖注入
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // 默认构造的首选构造函数
    // Preferred constructors for default construction?
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }

    // 没有特殊处理:只需使用无参数构造函数。 
    // No special handling: simply use no-arg constructor.
    return instantiateBean(beanName, mbd);
}
/**
    * Instantiate the given bean using its default constructor.
    * @param beanName the name of the bean
    * @param mbd the bean definition for the bean
    * @return a BeanWrapper for the new instance
    */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                    getInstantiationStrategy().instantiate(mbd, beanName, parent),
                    getAccessControlContext());
        }
        else {
            // 实例化
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        // 初始化BeanWrapper 包装一下返回
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}

通过Java反射或者CGLIB实例化

源码位置: org.springframework.beans.factory.support.SimpleInstantiationStrategy

@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
    // 如果不存在方法覆写,那就使用Java反射进行实例化,否则使用 CGLIB,
    // Don't override the class with CGLIB if no overrides.
    if (!bd.hasMethodOverrides()) {
        Constructor<?> constructorToUse;
        synchronized (bd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse == null) {
                // 获取bean对应的类
                final Class<?> clazz = bd.getBeanClass();
                // 
                if (clazz.isInterface()) {
                    throw new BeanInstantiationException(clazz, "Specified class is an interface");
                }
                try {
                    if (System.getSecurityManager() != null) {
                        constructorToUse = AccessController.doPrivileged(
                                (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                    }
                    else {
                        // 获取所有构造方法(包括public和private的)
                        constructorToUse = clazz.getDeclaredConstructor();
                    }
                    bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                }
                catch (Throwable ex) {
                    throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                }
            }
        }
        // 通过构造方法实例化
        return BeanUtils.instantiateClass(constructorToUse);
    }
    else {
        // 在方法覆写,利用 CGLIB 来完成实例化,需要依赖于 CGLIB 生成子类
        // Must generate CGLIB subclass.
        return instantiateWithMethodInjection(bd, beanName, owner);
    }
}

源码位置: BeanUtils::instantiateClass()

/**
    * Convenience method to instantiate a class using the given constructor.
    * <p>Note that this method tries to set the constructor accessible if given a
    * non-accessible (that is, non-public) constructor, and supports Kotlin classes
    * with optional parameters and default values.
    * @param ctor the constructor to instantiate
    * @param args the constructor arguments to apply (use {@code null} for an unspecified
    * parameter if needed for Kotlin classes with optional parameters and default values)
    * @return the new instance
    * @throws BeanInstantiationException if the bean cannot be instantiated
    * @see Constructor#newInstance
    */
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
    Assert.notNull(ctor, "Constructor must not be null");
    try {
        ReflectionUtils.makeAccessible(ctor);
        return (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
                KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
    }
    catch (InstantiationException ex) {
        throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
    }
    catch (IllegalAccessException ex) {
        throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
    }
    catch (IllegalArgumentException ex) {
        throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
    }
    catch (InvocationTargetException ex) {
        throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
    }
}
/**
  * Initialize the given BeanWrapper with the custom editors registered
  * with this factory. To be called for BeanWrappers that will create
  * and populate bean instances.
  * <p>The default implementation delegates to {@link #registerCustomEditors}.
  * Can be overridden in subclasses.
  * @param bw the BeanWrapper to initialize
  */
protected void initBeanWrapper(BeanWrapper bw) {
  bw.setConversionService(getConversionService());
  registerCustomEditors(bw);
}

源码位置: AbstractAutowireCapableBeanFactory

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

源码位置: DefaultSingletonBeanRegistry::addSingletonFactory();

/**
  * Add the given singleton factory for building the specified singleton
  * if necessary.
  * <p>To be called for eager registration of singletons, e.g. to be able to
  * resolve circular references.
  * @param beanName the name of the bean
  * @param singletonFactory the factory for the singleton object
  */
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
  Assert.notNull(singletonFactory, "Singleton factory must not be null");
  synchronized (this.singletonObjects) {
    if (!this.singletonObjects.containsKey(beanName)) {
      this.singletonFactories.put(beanName, singletonFactory);
      this.earlySingletonObjects.remove(beanName);
      this.registeredSingletons.add(beanName);
    }
  }
}

 

bean属性注入

AbstractAutowireCapableBeanFactory::populateBean()

/**
  * Populate the bean instance in the given BeanWrapper with the property values
  * from the bean definition.
  * @param beanName the name of the bean
  * @param mbd the bean definition for the bean
  * @param bw the BeanWrapper with bean instance
  */
@SuppressWarnings("deprecation")  // for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  if (bw == null) {
    if (mbd.hasPropertyValues()) {
      throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
    }
    else {
      // Skip property population phase for null instance.
      return;
    }
  }

  // 让任何 InstantiationAware BeanPostProcessors 有机会在设置属性之前修改 bean 的状态。 例如,这可以用于支持字段注入的样式。
  // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
  // state of the bean before properties are set. This can be used, for example,
  // to support styles of field injection.
  boolean continueWithPropertyPopulation = true;

  if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof InstantiationAwareBeanPostProcessor) {
        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
        // 
        if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
          continueWithPropertyPopulation = false;
          break;
        }
      }
    }
  }

  // 如果不需要属性注入,返回
  if (!continueWithPropertyPopulation) {
    return;
  }

  PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

  if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
    MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
    // autowirte_by_name 通过名字找到所有属性值 
    // Add property values based on autowire by name if applicable.
    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
      autowireByName(beanName, mbd, bw, newPvs);
    }
    // autowirte_by_type 根据bean对应的class类型设置属性值
    // Add property values based on autowire by type if applicable.
    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
      autowireByType(beanName, mbd, bw, newPvs);
    }
    pvs = newPvs;
  }

  boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

  PropertyDescriptor[] filteredPds = null;
  if (hasInstAwareBpps) {
    if (pvs == null) {
      pvs = mbd.getPropertyValues();
    }
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof InstantiationAwareBeanPostProcessor) {
        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
        PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
        if (pvsToUse == null) {
          if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
          }
          // 各种BeanPostProcessor 会执行到这里 比如 AutowiredAnnotationBeanPostProcessor 对采用 @Autowired、@Value 注解的依赖进行设值
          pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
          if (pvsToUse == null) {
            return;
          }
        }
        pvs = pvsToUse;
      }
    }
  }
  if (needsDepCheck) {
    if (filteredPds == null) {
      filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
    }
    checkDependencies(beanName, mbd, filteredPds, pvs);
  }

  if (pvs != null) {
    // 设置bean实例的属性值
    applyPropertyValues(beanName, mbd, bw, pvs);
  }
}

AbstractAutowireCapableBeanFactory::applyPropertyValues()

/**
    * Apply the given property values, resolving any runtime references
    * to other beans in this bean factory. Must use deep copy, so we
    * don't permanently modify this property.
    * @param beanName the bean name passed for better exception information
    * @param mbd the merged bean definition
    * @param bw the BeanWrapper wrapping the target object
    * @param pvs the new property values
    */
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs.isEmpty()) {
        return;
    }

    if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
        ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    }

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                bw.setPropertyValues(mpvs);
                return;
            }
            catch (BeansException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    }
    else {
        original = Arrays.asList(pvs.getPropertyValues());
    }

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

    // Create a deep copy, resolving any references for values.
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            deepCopy.add(pv);
        }
        else {
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            // 解析对应的值 
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            boolean convertible = bw.isWritableProperty(propertyName) &&
                    !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                // 解析对应的值
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // Possibly store converted value in merged bean definition,
            // in order to avoid re-conversion for every created bean instance.
            if (resolvedValue == originalValue) {
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            }
            else if (convertible && originalValue instanceof TypedStringValue &&
                    !((TypedStringValue) originalValue).isDynamic() &&
                    !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            }
            else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }

    // Set our (possibly massaged) deep copy.
    try {
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    }
    catch (BeansException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}
/**
  * Convert the given value for the specified target property.
  */
@Nullable
private Object convertForProperty(
    @Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {

  if (converter instanceof BeanWrapperImpl) {
    // 这里
    return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
  }
  else {
    PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
    MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
    return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
  }
}

BeanWrapperImpl::convertForProperty

public Object convertForProperty(@Nullable Object value, String propertyName) throws TypeMismatchException {
  CachedIntrospectionResults cachedIntrospectionResults = getCachedIntrospectionResults();
  PropertyDescriptor pd = cachedIntrospectionResults.getPropertyDescriptor(propertyName);
  if (pd == null) {
    throw new InvalidPropertyException(getRootClass(), getNestedPath() + propertyName,
        "No property '" + propertyName + "' found");
  }
  TypeDescriptor td = cachedIntrospectionResults.getTypeDescriptor(pd);
  if (td == null) {
    td = cachedIntrospectionResults.addTypeDescriptor(pd, new TypeDescriptor(property(pd)));
  }
  return convertForProperty(propertyName, null, value, td);
}

AbstractNestablePropertyAccessor::convertForProperty

@Nullable
protected Object convertForProperty(
    String propertyName, @Nullable Object oldValue, @Nullable Object newValue, TypeDescriptor td)
    throws TypeMismatchException {

  return convertIfNecessary(propertyName, oldValue, newValue, td.getType(), td);
}

源码位置: org.springframework.beans.AbstractNestablePropertyAccessor::convertIfNecessary

@Nullable
private Object convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue,
        @Nullable Object newValue, @Nullable Class<?> requiredType, @Nullable TypeDescriptor td)
        throws TypeMismatchException {

    Assert.state(this.typeConverterDelegate != null, "No TypeConverterDelegate");
    try {
        return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType, td);
    }
    catch (ConverterNotFoundException | IllegalStateException ex) {
        PropertyChangeEvent pce =
                new PropertyChangeEvent(getRootInstance(), this.nestedPath + propertyName, oldValue, newValue);
        throw new ConversionNotSupportedException(pce, requiredType, ex);
    }
    catch (ConversionException | IllegalArgumentException ex) {
        PropertyChangeEvent pce =
                new PropertyChangeEvent(getRootInstance(), this.nestedPath + propertyName, oldValue, newValue);
        throw new TypeMismatchException(pce, requiredType, ex);
    }
}

源码位置: BeanDefinitionValueResolver::resolveValueIfNecessary()

/**
    * Given a PropertyValue, return a value, resolving any references to other
    * beans in the factory if necessary. The value could be:
    * <li>A BeanDefinition, which leads to the creation of a corresponding
    * new bean instance. Singleton flags and names of such "inner beans"
    * are always ignored: Inner beans are anonymous prototypes.
    * <li>A RuntimeBeanReference, which must be resolved.
    * <li>A ManagedList. This is a special collection that may contain
    * RuntimeBeanReferences or Collections that will need to be resolved.
    * <li>A ManagedSet. May also contain RuntimeBeanReferences or
    * Collections that will need to be resolved.
    * <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
    * or Collection that will need to be resolved.
    * <li>An ordinary object or {@code null}, in which case it's left alone.
    * @param argName the name of the argument that the value is defined for
    * @param value the value object to resolve
    * @return the resolved object
    */
@Nullable
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
    // We must check each value to see whether it requires a runtime reference
    // to another bean to be resolved.
    if (value instanceof RuntimeBeanReference) {
        RuntimeBeanReference ref = (RuntimeBeanReference) value;
        return resolveReference(argName, ref);
    }
    else if (value instanceof RuntimeBeanNameReference) {
        String refName = ((RuntimeBeanNameReference) value).getBeanName();
        refName = String.valueOf(doEvaluate(refName));
        if (!this.beanFactory.containsBean(refName)) {
            throw new BeanDefinitionStoreException(
                    "Invalid bean name '" + refName + "' in bean reference for " + argName);
        }
        return refName;
    }
    else if (value instanceof BeanDefinitionHolder) {
        // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
        BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
        return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
    }
    else if (value instanceof BeanDefinition) {
        // Resolve plain BeanDefinition, without contained name: use dummy name.
        BeanDefinition bd = (BeanDefinition) value;
        String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
                ObjectUtils.getIdentityHexString(bd);
        return resolveInnerBean(argName, innerBeanName, bd);
    }
    else if (value instanceof ManagedArray) {
        // May need to resolve contained runtime references.
        ManagedArray array = (ManagedArray) value;
        Class<?> elementType = array.resolvedElementType;
        if (elementType == null) {
            String elementTypeName = array.getElementTypeName();
            if (StringUtils.hasText(elementTypeName)) {
                try {
                    elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
                    array.resolvedElementType = elementType;
                }
                catch (Throwable ex) {
                    // Improve the message by showing the context.
                    throw new BeanCreationException(
                            this.beanDefinition.getResourceDescription(), this.beanName,
                            "Error resolving array type for " + argName, ex);
                }
            }
            else {
                elementType = Object.class;
            }
        }
        return resolveManagedArray(argName, (List<?>) value, elementType);
    }
    else if (value instanceof ManagedList) {
        // May need to resolve contained runtime references.
        return resolveManagedList(argName, (List<?>) value);
    }
    else if (value instanceof ManagedSet) {
        // May need to resolve contained runtime references.
        return resolveManagedSet(argName, (Set<?>) value);
    }
    else if (value instanceof ManagedMap) {
        // May need to resolve contained runtime references.
        return resolveManagedMap(argName, (Map<?, ?>) value);
    }
    else if (value instanceof ManagedProperties) {
        Properties original = (Properties) value;
        Properties copy = new Properties();
        original.forEach((propKey, propValue) -> {
            if (propKey instanceof TypedStringValue) {
                propKey = evaluate((TypedStringValue) propKey);
            }
            if (propValue instanceof TypedStringValue) {
                propValue = evaluate((TypedStringValue) propValue);
            }
            if (propKey == null || propValue == null) {
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Error converting Properties key/value pair for " + argName + ": resolved to null");
            }
            copy.put(propKey, propValue);
        });
        return copy;
    }
    else if (value instanceof TypedStringValue) {
        // Convert value to target type here.
        TypedStringValue typedStringValue = (TypedStringValue) value;
        Object valueObject = evaluate(typedStringValue);
        try {
            Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
            if (resolvedTargetType != null) {
                return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
            }
            else {
                return valueObject;
            }
        }
        catch (Throwable ex) {
            // Improve the message by showing the context.
            throw new BeanCreationException(
                    this.beanDefinition.getResourceDescription(), this.beanName,
                    "Error converting typed String value for " + argName, ex);
        }
    }
    else if (value instanceof NullBean) {
        return null;
    }
    else {
        return evaluate(value);
    }
}

 

初始化bean initializeBean

/**
    * Initialize the given bean instance, applying factory callbacks
    * as well as init methods and bean post processors.
    * <p>Called from {@link #createBean} for traditionally defined beans,
    * and from {@link #initializeBean} for existing bean instances.
    * @param beanName the bean name in the factory (for debugging purposes)
    * @param bean the new bean instance we may need to initialize
    * @param mbd the bean definition that the bean was created with
    * (can also be {@code null}, if given an existing bean instance)
    * @return the initialized bean instance (potentially wrapped)
    * @see BeanNameAware
    * @see BeanClassLoaderAware
    * @see BeanFactoryAware
    * @see #applyBeanPostProcessorsBeforeInitialization
    * @see #invokeInitMethods
    * @see #applyBeanPostProcessorsAfterInitialization
    */
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        // 处理各种Aware
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // 初始化之前应用各种BeanPostProcessors
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        // 调用初始化方法
        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()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

调用各种Aware invokeAwareMethods

源码位置: AbstractAutowireCapableBeanFactory::invokeAwareMethods

private void invokeAwareMethods(final String beanName, final Object bean) {
  if (bean instanceof Aware) {
    if (bean instanceof BeanNameAware) {
      ((BeanNameAware) bean).setBeanName(beanName);
    }
    if (bean instanceof BeanClassLoaderAware) {
      ClassLoader bcl = getBeanClassLoader();
      if (bcl != null) {
        ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
      }
    }
    if (bean instanceof BeanFactoryAware) {
      ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
    }
  }
}

初始化之前应用各种BeanPostProcessors applyBeanPostProcessorsBeforeInitialization

源码位置: AbstractAutowireCapableBeanFactory::applyBeanPostProcessorsBeforeInitialization

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

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

源码位置: ApplicationContextAwareProcessor::postProcessBeforeInitialization()

@Override
@Nullable
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
  AccessControlContext acc = null;

  if (System.getSecurityManager() != null &&
      (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
          bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
          bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
    acc = this.applicationContext.getBeanFactory().getAccessControlContext();
  }

  if (acc != null) {
    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
      invokeAwareInterfaces(bean);
      return null;
    }, acc);
  }
  else {
    // 执行各种Aware 
    invokeAwareInterfaces(bean);
  }

  return bean;
}
private void invokeAwareInterfaces(Object bean) {
  if (bean instanceof Aware) {
    if (bean instanceof EnvironmentAware) {
      ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
    }
    if (bean instanceof EmbeddedValueResolverAware) {
      ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
    }
    if (bean instanceof ResourceLoaderAware) {
      ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
    }
    if (bean instanceof ApplicationEventPublisherAware) {
      ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
    }
    if (bean instanceof MessageSourceAware) {
      ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
    }
    if (bean instanceof ApplicationContextAware) {
      ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
    }
  }
}

调用初始化方法 invokeInitMethods()

源码位置: AbstractAutowireCapableBeanFactory::invokeInitMethods()

/**
    * 现在给一个 bean 一个反应的机会,它的所有属性都已设置,并有机会了解它拥有的 bean 工厂(这个对象)。这意味着检查 bean 是否实现了 InitializingBean 或定义了自定义的 init 方法,如果是,则调用必要的回调。
    * 
    * Give a bean a chance to react now all its properties are set,
    * and a chance to know about its owning bean factory (this object).
    * This means checking whether the bean implements InitializingBean or defines
    * a custom init method, and invoking the necessary callback(s) if it does.
    * @param beanName the bean name in the factory (for debugging purposes)
    * @param bean the new bean instance we may need to initialize
    * @param mbd the merged bean definition that the bean was created with
    * (can also be {@code null}, if given an existing bean instance)
    * @throws Throwable if thrown by init methods or by the invocation process
    * @see #invokeCustomInitMethod
    */
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
        throws Throwable {
    // Bean实现了InitializingBean接口
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            // 调用bean的afterPropertiesSet方法
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            // 调用自定义初始化方法
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}
/**
    * Give a bean a chance to react now all its properties are set,
    * and a chance to know about its owning bean factory (this object).
    * This means checking whether the bean implements InitializingBean or defines
    * a custom init method, and invoking the necessary callback(s) if it does.
    * @param beanName the bean name in the factory (for debugging purposes)
    * @param bean the new bean instance we may need to initialize
    * @param mbd the merged bean definition that the bean was created with
    * (can also be {@code null}, if given an existing bean instance)
    * @throws Throwable if thrown by init methods or by the invocation process
    * @see #invokeCustomInitMethod
    */
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
        throws Throwable {

    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            // 调用自定义初始化方法
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}
/**
    * Invoke the specified custom init method on the given bean.
    * Called by invokeInitMethods.
    * <p>Can be overridden in subclasses for custom resolution of init
    * methods with arguments.
    * @see #invokeInitMethods
    */
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {

    String initMethodName = mbd.getInitMethodName();
    Assert.state(initMethodName != null, "No init method set");
    // 通过反射获取initMethod
    Method initMethod = (mbd.isNonPublicAccessAllowed() ?
            BeanUtils.findMethod(bean.getClass(), initMethodName) :
            ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

    if (initMethod == null) {
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Could not find an init method named '" +
                    initMethodName + "' on bean with name '" + beanName + "'");
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("No default init method named '" + initMethodName +
                        "' found on bean with name '" + beanName + "'");
            }
            // Ignore non-existent default lifecycle methods.
            return;
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }
    Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            ReflectionUtils.makeAccessible(methodToInvoke);
            return null;
        });
        try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
                    methodToInvoke.invoke(bean), getAccessControlContext());
        }
        catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    }
    else {
        try {
            ReflectionUtils.makeAccessible(initMethod);
            initMethod.invoke(bean);
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

初始化之后应用各种BeanPostProcessors

源码位置: AbstractAutowireCapableBeanFactory::applyBeanPostProcessorsAfterInitialization

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

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

registerDisposableBeanIfNecessary

AbstractBeanFactory::registerDisposableBeanIfNecessary()

/**
  * Add the given bean to the list of disposable beans in this factory,
  * registering its DisposableBean interface and/or the given destroy method
  * to be called on factory shutdown (if applicable). Only applies to singletons.
  * @param beanName the name of the bean
  * @param bean the bean instance
  * @param mbd the bean definition for the bean
  * @see RootBeanDefinition#isSingleton
  * @see RootBeanDefinition#getDependsOn
  * @see #registerDisposableBean
  * @see #registerDependentBean
  */
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
  AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
  if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
    if (mbd.isSingleton()) {
      // 注册一个DisposableBean实现,该实现执行给定bean的所有销毁工作:DestructionAwareBeanPostProcessors、DisposableBean接口、自定义销毁方法。
      // Register a DisposableBean implementation that performs all destruction
      // work for the given bean: DestructionAwareBeanPostProcessors,
      // DisposableBean interface, custom destroy method.
      registerDisposableBean(beanName,
          new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
    }
    else {
      // A bean with a custom scope...
      Scope scope = this.scopes.get(mbd.getScope());
      if (scope == null) {
        throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
      }
      scope.registerDestructionCallback(beanName,
          new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
    }
  }
}

参考资料

[1] Spring三十五问,四万字+五十图详解!
[2] spring-ioc
[3] mini-spring
[4] Spring IoC - IoC 容器初始化 源码解析
[5] Spring IoC - 依赖注入 源码解析
[6] Spring Bean 生命周期 (实例结合源码彻底讲透)
[7] 5. The IoC container
[8] 浅析spring——IOC 之 分析 Bean 的生命周期
[9] 谈谈Spring中都用到了那些设计模式
[10] 源码解析Spring Bean的生命周期
[11] Spring(三)核心容器 - ApplicationContext 上下文启动准备
[12] IOC容器初始化过程
[13] Spring源码分析一:容器的刷新 - refresh()
[14] 导读|5分钟轻松了解Spring基础知识-Spring编程常见错误50例