Spring依赖注入

依赖注入是什么

Spring中依赖注入是如何把一个Bean装配到BeanFactory里

依赖注入做了哪些事情

beanName 解析转换
手动注册Bean检测
双亲容器检测
依赖初始化(递归)
★ 创建singleton 实例
对象实例化
属性装配
处理Bean创建之后的各种回调事件

源码解读

Spring IoC 依赖注入的入口是 getBean()

TODO 流程图

getBean()

源码位置 AbstractBeanFactory::getBean(String name)

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

doGetBean()

源码位置: AbstractBeanFactory::doGetBean()

作用

beanName 解析转换
检测 手动注册Bean
双亲容器检测
依赖初始化(递归)
创建Bean createBean()

/**
     * 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 {

     // 获取到真正beanName
     // 处理两种情况,1.把FactoryBean的前缀"&"给去了;2.将别名beanName转化成真正的beanName
     final String beanName = transformedBeanName(name);
     Object bean;

     // 检测已经注册的Bean,保证不重复创建  
     // 这块注意bean注册时的循环依赖  详细逻辑看getSingleton(beanName)方法 
     // Eagerly check singleton cache for manually registered singletons.
     Object sharedInstance = getSingleton(beanName);
     if (sharedInstance != null && args == null) {
          if (logger.isTraceEnabled()) {
               // 打印日志 返回着急的还未完成初始化的bean缓存示例 + beanName  并提示循环引用的结果
               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 {
                    // 打印日志  返回单例bean的缓存实例 + 实际beanName
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
               }
          }
          // 如果目前获得的sharedInstance 不是FactoryBean,那bean就赋值成sharedInstance,直接返回
          // 如果是FactoryBean就返回FactoryBean创建的实例,
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
     }

     else {
          // 如果我们已经在创建这个bean实例,则失败: 我们假设在一个循环引用中。
          // Fail if we're already creating this bean instance:
          // We're assumably within a circular reference.
          if (isPrototypeCurrentlyInCreation(beanName)) {
               throw new BeanCurrentlyInCreationException(beanName);
          }

          // 检查下这个BeanDefinition是否存在
          // Check if bean definition exists in this factory.
          BeanFactory parentBeanFactory = getParentBeanFactory();
          if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
               // 当前容器没有这个BeanDefinition,去parent容器去找
               // 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) {
               markBeanAsCreated(beanName);
          }

          try {
               final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
               checkMergedBeanDefinition(mbd, beanName, args);

               // 先初始化依赖的所有Bean
               // 注意,这里的依赖指的是 depends-on 中定义的依赖
               // 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)) {
                              // 通过depends-on定义造成的循环依赖
                              throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                         }
                         // 注册依赖关系
                         // 这么做的原因是Spring在即将进行bean销毁的时候会【首先销毁被依赖的bean】。
                         // 看SpringBean的初始化和销毁顺序就知道了,依赖关系的保存目的就是这个依赖关系的保存是通过一个ConcurrentHashMap<String, Set>完成的,key是bean的真实名字。
                         registerDependentBean(dep, beanName);
                         try {
                              // 先去初始化被依赖项
                              // 递归然后反递归回来
                              getBean(dep);
                         }
                         catch (NoSuchBeanDefinitionException ex) {
                              throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                         }
                    }
               }

               //  如果是 singleton scope 的,创建 singleton 的实例
               // Create bean instance.
               if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                         try {
                              // 重要  创建Bean
                              return createBean(beanName, mbd, args);
                         }
                         catch (BeansException ex) {
                              // Explicitly remove instance from singleton cache: It might have been put there
                              // eagerly by the creation process, to allow for circular reference resolution.
                              // Also remove any beans that received a temporary reference to the bean.
                              destroySingleton(beanName);
                              throw ex;
                         }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
               }

               // 如果是 prototype scope 的,创建 prototype 的实例
               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 + "'");
                    }

                    // 如果不是 singleton 和 prototype 的话,需要委托给相应的实现类来处理
                    
                    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;
}

createBean()

源码位置: AbstractAutowireCapableBeanFactory::createBean()


/**
     * 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;

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

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

     try {
          // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
          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);
     }
}

doCreateBean()

源码位置: AbstractAutowireCapableBeanFactory::doCreateBean()

步骤概览:

开始是单例的话要先清除缓存;
实例化bean,将BeanDefinition转换为BeanWrapper;
使用MergedBeanDefinitionPostProcessor,Autowired注解就是通过此方法实现类型的预解析;
解决循环依赖问题;
填充属性,将属性填充到bean实例中;
注册DisposableBean;
创建完成并返回。

三个关注点:

createBeanInstance() 实例化
populateBean(); 属性装配
initializeBean() 处理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 {

    // 这个BeanWrapper是创建出来持有对象的
    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        // 如果是singleton,先把缓存中的同名bean消除
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 重要   
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // 涉及接口:MergedBeanDefinitionPostProcessor
    // 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;
        }
    }

    // 这里是为了解决循环依赖的,先把初步实例化的Bean实例的引用缓存起来,暴露出去
    // 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 {
        // 重要  属性装配
        // 前面的实例只是实例化,没有装配属性 
        populateBean(beanName, mbd, instanceWrapper);
        // 处理bean初始化完成后的各种回调  
        // 比如init-method、以及 InitializingBean 接口、还有 BeanPostProcessor 接口 
        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);
        }
    }

    // 如果该beanName对象已经注册单例模式,则从单例中获取,并判断获取到的bean实例(B)与BeanWrapper中的bean实例(A)是同一个实例,如果是,则返回A或者B,如果不是,则递归找出它的依赖bean。
    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        // earlySingletonReference只有在检测到有循环依赖的情况下才会不为空
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                // 两个是同一个引用,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.");
                }
            }
        }
    }

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

    return exposedObject;
}

重要 createBeanInstance() 实例化

/**
 * 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);

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

     // 如果工厂方法不为空,则是用工厂方法初始化  FactoryBean 
    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?
    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);
}

重要 populateBean() 属性装配

作用: 根据autowire类型进行autowire by name,by type或者是直接进行设置

源码位置: 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;
        }
    }

    // 扩展点  InstantiationAwareBeanPostProcessor 的实现类可以在这里对 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;
                // 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理
                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);
        // 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系
        // Add property values based on autowire by name if applicable.
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
            // 通过名称装配
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // 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;
                // 执行后置处理器,填充属性,完成自动装配 
                // 比如 @Autowirte @Value实现原理就是在这里调用到AutowiredAnnotationBeanPostProcessor扩展点
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    if (filteredPds == null) {
                        filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    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);
    }
}

AbstractPropertyAccessor.setPropertyValues
BeanWrapperImpl::setValue

重要 initializeBean() 处理Bean初始化之后的各种回调事件

/**
 * 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>) () -> {
            // 色值各种Aware BeanNameAware、BeanClassLoaderAware、BeanFactoryAware 
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        // 设置各种Aware BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // BeanPostProcessor 的 postProcessBeforeInitialization 回调 
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        // init-methods 或者是实现了InitializingBean接口,会调用afterPropertiesSet() 方法
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        // BeanPostProcessor 的 postProcessAfterInitialization 回调 
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

applyBeanPostProcessorsBeforeInitialization

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

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

invokeInitMethods

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

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

参考

[1] Spring IoC - 依赖注入 源码解析
[2] 关于Spring IOC (DI-依赖注入)你需要知道的一切