执行Bean属性设置方法流程.最下有截图.可根据截图理解调用链

设置Bean属性设置调用之前Bean创建调用方法

  1. 从refresh()方法第十一步finishBeanFactoryInitialization()方法最后一行preInstantiateSingletons(DefaultListableBeanFactory实现)

  2. 然后调用AbstractBeanFactory.getBean--> doGetBean.从这里开启Bean创建以及三级缓存解决流程

  3. AbstractBeanFactory.doGetBean中当Bean存在于三级缓存中则会从三级缓存中获取getSingleton(beanName),否则会执行创建对象过程getSingleton(String beanName, ObjectFactory<?> singletonFactory)

doGetBean

protected <T> T doGetBean(
        String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
        throws BeansException {
    String beanName = transformedBeanName(name);
    Object beanInstance;
    // 这里从三级缓存中获取实例,三级缓存中没有则执行创建实例
    Object sharedInstance = getSingleton(beanName);

    // ...省略。处理预先加载@DependsOn标记的依赖Bean,如果在这里有循环依赖则直接抛出异常
    // Create bean instance.在这里创建Bean实例.即那个createBaen的lambda回调表达式方法.
    if (mbd.isSingleton()) {
        sharedInstance = getSingleton(beanName, () -> {
            try {
                return createBean(beanName, mbd, args);
            }
            catch (BeansException ex) {
                // 创建异常删除单例Bean缓存.
                destroySingleton(beanName);
                throw ex;
            }
        });
        beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
    }

}
public Object getSingleton(String beanName) {
    return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    // 从三级缓存中获取Bean
    Object singletonObject = this.singletonObjects.get(beanName);
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        singletonObject = this.earlySingletonObjects.get(beanName);
        if (singletonObject == null && allowEarlyReference) {
            synchronized (this.singletonObjects) {
                // Consistent creation of early reference within full singleton lock
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                    singletonObject = this.earlySingletonObjects.get(beanName);
                    if (singletonObject == null) {
                        ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                        if (singletonFactory != null) {
                            // 在创建Bean的过程中会将自身加入实现ObjectFactory函数式方法lambda表达式中
                            // 出现循环依赖时,会执行它提前执行AOP等早期创建的补偿方法.
                            // 在第五步加入了该方法的回调工厂lambda函数表达式如下
                            // addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
                            // 在第六步通过依赖注入再次调用getBean时,如果有循环依赖则会提前执行获取该Bean的方法
                            // getEarlyBeanRefrence涉及到了Bean提前创建的AOP代理检查创建工作
                            singletonObject = singletonFactory.getObject();
                            this.earlySingletonObjects.put(beanName, singletonObject);
                            this.singletonFactories.remove(beanName);
                        }
                    }
                }
            }
        }
    }
    return singletonObject;
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    // 多余代码不展示. 单例Bean创建完添加到一级缓存中
    Object singletonObject = this.singletonObjects.get(beanName);
    if(singletonObject == null){
        try {
            // 这里getObject执行的是上面() -> {
            //                                  try {
            //                                      return createBean(beanName, mbd, args);
            //                                  }
            singletonObject = singletonFactory.getObject();
            newSingleton = true;
        }
        catch (IllegalStateException ex) {
            // 是否创建过检查
            singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                throw ex;
            }
        }finally {
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = null;
            }
            afterSingletonCreation(beanName);
        }
        if (newSingleton) {
            addSingleton(beanName, singletonObject);
        }
    }
   return singletonObject 
}  
  1. AbstractCapableBeanFactory.create,postProcessorBeforInstantiation方法没有创建Bean则会执行本类的doCreateBean
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {
    // 多余不展示,执行了InstantiationAwareBeanPostProcessor.postProcessorBeforInstantiation方法
    // 
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
}
  1. 该方法创建一个实例,通过addSingletonFactory加入到三级缓存中.会加入一个调用生成Bean代理lambda表达式SmartInstantiationAwareBeanPostProcessor.getEarlyBeanReference会调用Abstract***Creator.wrapIfNecessary-->createProxy方法.
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {
    // 创建Bean.执行MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition
    // 是否早期暴露出去到三级缓存中. 单例、支持循环依赖、正在创建
    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");
        }
        // 将该Bean实例封装到ObjectFactory中添加到三级缓存.
        // () -> getEarlyBeanReference(beanName, mbd, bean)是一个lambda函数表达式.也是ObjectFactory.getObject()
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }
    try {
        // 在这里执行Bean属性注入以及循环依赖解决
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }catch(Exception e){
        // 异常执行
    }
    return exposedObject;
}

// Abstract***Creator
public Object getEarlyBeanReference(Object bean, String beanName) {
    Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
    this.earlyProxyReferences.put(cacheKey, bean);
    return this.wrapIfNecessary(bean, beanName, cacheKey);
}    
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    // 省略了其他代码,这里判断需要做代理则会执行创建代理工作
    Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
}
  1. populateBean方法主要执行注入属性方法调用AutowiredAnnotationBeanPostProcessor等后置执行器查找依赖进行注入
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    // 多余方法不写
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
            // 主要这行.执行AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor的postProcessProperties方法.
            // 这两个类负责常规注解属性和autowired注解属性判断和注入
            PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
                if (filteredPds == null) {
                    filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }
                pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    return;
                }
            }
            pvs = pvsToUse;
        }
    }
}

// 执行的注解后置处理器注入Bean
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        // 这里会跳到InjectionMetadata.inject方法中.
        metadata.inject(bean, beanName, pvs);
    }
    catch (BeanCreationException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
    }
    return pvs;
}

// InjectionMetadata.inject方法.还是执行子类流程.
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    Collection<InjectedElement> checkedElements = this.checkedElements;
    Collection<InjectedElement> elementsToIterate =
            (checkedElements != null ? checkedElements : this.injectedElements);
    if (!elementsToIterate.isEmpty()) {
        for (InjectedElement element : elementsToIterate) {
            // 这里不要看本身实现,看AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject方法
            element.inject(target, beanName, pvs);
        }
    }
}

// AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject方法
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    // 省去其他代码
    value = resolveFieldValue(field, bean, beanName);
}

// AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue方法就是bean工厂中获取对应依赖的Bean了
private Object resolveFieldValue(Field field, Object bean, @Nullable String beanName) {
    // 省去其他代码
    try {
        value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
    }
}
  1. DefaultListableBeanFactory工厂获取依赖Bean调用链,执行Bean工厂的getBean方法.到这循环依赖成了一个回环,反复执行第二步.
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
        @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    // 多余代码不描述
    if (result == null) {
            // 执行本类的解析依赖操作返回对应的依赖Bean
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
}

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
            @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    if (autowiredBeanNames != null) {
        autowiredBeanNames.add(autowiredBeanName);
    }
    if (instanceCandidate instanceof Class) {
        // 最后一次调用解析DependencyDescriptor.resolveCandidate方法
        instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
    }
}

// 执行Bean工厂的getBean方法.到这循环依赖成了一个回环,反复执行第二步.
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
        throws BeansException {

    return beanFactory.getBean(beanName);
}
  1. 拓展: 提前获取Bean.执行AOP检查创建.保证流程完整Abstract***Creator(SmartInstantiationAwareBeanPostProcessor实现类)
public Object getEarlyBeanReference(Object bean, String beanName) {
    Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
    this.earlyProxyReferences.put(cacheKey, bean);
    return this.wrapIfNecessary(bean, beanName, cacheKey);
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    } else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    } else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {
        Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
        if (specificInterceptors != DO_NOT_PROXY) {
            this.advisedBeans.put(cacheKey, Boolean.TRUE);
            // 如果需要创建代理则创建对应代理
            Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        } else {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }
    } else {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }
}

先开始加载BeanA

A依赖B

BeanA依赖于B,所以调用链调用到getBean(LoopB).

B依赖A

BeanB依赖于A.此时三级缓存已经有A,beanFactory.getBean会走第一个getSingleton查找三级缓存并且getObject

在这里插入图片描述