Spring 的循环依赖 三级缓存问题

缓存层级

名称

描述

第一层缓存

singletonObjects

单例对象缓存池,存放的 Bean 已经实例化、属性赋值、完全初始化好(成品)

第二层缓存

earlySingletonObjects

早期单例对象缓存池,存放的 Bean 已经实例化但尚未属性赋值、未执行 init 方法(半成品)

第三层缓存

singletonFactories

单例工厂的缓存

测试代码

@Component
public class AService {

    @Autowired
    BService bService;

    public BService getbService() {
        return bService;
    }

    public void setbService(BService bService) {
        this.bService = bService;
    }
}
@Component
public class BService {

    @Autowired
    AService aService;

    public AService getaService() {
        return aService;
    }

    public void setaService(AService aService) {
        this.aService = aService;
    }
}
public class MainTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("tools");

        AService bean = context.getBean(AService.class);
        System.out.println(bean.getbService());

    }

}

初始化AService

  • 初始化前的准备部分(非循环依赖的重点):AbstractApplicationContextrefresh()方法开始看,finishBeanFactoryInitialization(beanFactory)
@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
     //....省略
        try {
          //....省略
            
            // Instantiate all remaining (non-lazy-init) singletons.
            //前面的所有准备工作都已经完成,就差初始化bean
            finishBeanFactoryInitialization(beanFactory);

        }
    }
}
  • 初始化前的准备部分(非循环依赖的重点):AbstractApplicationContext.finishBeanFactoryInitialization()
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	
    //...省略
    
		// Instantiate all remaining (non-lazy-init) singletons.
    	//真正的初始化方法
		beanFactory.preInstantiateSingletons();
	}
  • 初始化前的准备部分(非循环依赖的重点):DefaultListableBeanFactory.preInstantiateSingletons()
@Override
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }

    // 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.
    //从 beanDefinitionNames 获取所有的bean模板
    List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        //不是抽象类、是单例、不是懒加载的
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            //是否是 factoryBean 创建
            if (isFactoryBean(beanName)) {
                final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                boolean isEagerInit;
                if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                    isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                        @Override
                        public Boolean run() {
                            return ((SmartFactoryBean<?>) factory).isEagerInit();
                        }
                    }, getAccessControlContext());
                }
                else {
                    isEagerInit = (factory instanceof SmartFactoryBean &&
                                   ((SmartFactoryBean<?>) factory).isEagerInit());
                }
                if (isEagerInit) {
                    getBean(beanName);
                }
            }
            else {
                //初始化所有不是 factoryBean 创建的
                //包括自定义bean的初始化
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    //...省略
}
  • getBean()开始,真正的bean初始化方法

AbstractBeanFactory.getBean(),doGetBean()

@Override
public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(
    final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
    throws BeansException {

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

    // Eagerly check singleton cache for manually registered singletons.
    //首先初始化AService
    //先从三级缓存中查询,首次初始化肯定返回 null
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isDebugEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                             "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        //如果已经创建了该单例的原型bean,则抛出异常
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // Check if bean definition exists in this factory.
        //从 ParentBeanFactory 中获取,如果存在
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }

        //标记bean已创建或正在创建
        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }

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


           // 先初始化依赖的所有 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 + "'");
                    }
                     // 注册一下依赖关系
                    registerDependentBean(dep, beanName);
                    try {
                         // 先初始化被依赖项
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // Create bean instance.
            //开始真正的创建bean
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        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);
            }

        
            //...省略后面的原型bean与非singleton 和 prototype的创建
    return (T) bean;
}
  • AbstractAutowireCapableBeanFactory.createBean().doCreateBean()
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {

    //...省略

    //doCreateBean:创建bean方法
   Object beanInstance = doCreateBean(beanName, mbdToUse, args);
   if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
   }
   return beanInstance;
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      throws BeanCreationException {

   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
	//从factoryBean中获取
    if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
    //为 null 代表不是factoryBean
   if (instanceWrapper == null) {
       //1、重点方法,创建bean实例,但不进行属性赋值与初始化
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
    //AService的bean
   final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
   Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
   mbd.resolvedTargetType = beanType;

    //...省略不重要的部分

    
    //开始解决循环依赖问题
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      if (logger.isDebugEnabled()) {
         logger.debug("Eagerly caching bean '" + beanName +
               "' to allow for resolving potential circular references");
      }
       
       //addSingletonFactory:将AService添加到三级缓存,并从二级缓存中移除(当前并不在于二级缓存)
      addSingletonFactory(beanName, new ObjectFactory<Object>() {
         @Override
         public Object getObject() throws BeansException {
            return getEarlyBeanReference(beanName, mbd, bean);
         }
      });
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
       //属性赋值,包括了对循环依赖的解决
       //当进行属性赋值时发现需要引用BService,但是BService并没有进行初始化,则先进行BService的初始化
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
          //初始化方法包括 init、和beanPostProcessor回调
         exposedObject = initializeBean(beanName, exposedObject, mbd);
      }
   }

    //...暂时忽略后面代码
}
//bean 实例化后执行的缓存方法
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(singletonFactory, "Singleton factory must not be null");
		synchronized (this.singletonObjects) {
            //bean都还没有初始化完,肯定不在一级缓存中
			if (!this.singletonObjects.containsKey(beanName)) {
                //将AService添加到三级缓存
				this.singletonFactories.put(beanName, singletonFactory);
                //从二级缓存中删除(当前本身就不存在)
				this.earlySingletonObjects.remove(beanName);
				this.registeredSingletons.add(beanName);
			}
		}
	}

到目前为止,AService已经实例化成功,并且存在于第三级缓存中,接下来就是属性赋值

  • populateBean()属性赋值方法,先初始化依赖的bean
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    // bean 实例的所有属性都在这里了
   PropertyValues pvs = mbd.getPropertyValues();

   if (bw == null) {
      if (!pvs.isEmpty()) {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      }
      else {
         // Skip property population phase for null instance.
         return;
      }
   }

	// 到这步的时候,bean 实例化完成(通过工厂方法或构造方法),但是还没开始属性设值,
   // InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改,
   // 我也没找到有实际的使用,所以我们暂且忽略这块吧
   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;
   }

   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

      // Add property values based on autowire by name if applicable.
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }

      // Add property values based on autowire by type if applicable.
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }

      pvs = newPvs;
   }

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

   if (hasInstAwareBpps || needsDepCheck) {
      PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      if (hasInstAwareBpps) {
         for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
               // 重点在这:注意这里会有个: AutowiredAnnotationBeanPostProcessor
               // 对采用 @Autowired、@Value 注解的依赖进行设值,解决循环依赖问题
               InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
               pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvs == null) {
                  return;
               }
            }
         }
      }
      if (needsDepCheck) {
         checkDependencies(beanName, mbd, filteredPds, pvs);
      }
   }

     // 设置 bean 实例的属性值
   applyPropertyValues(beanName, mbd, bw, pvs);
}
  • 通过AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues()的方法创建依赖的bean
/*
	pvs:空的 MutablePropertyValues 对象
	bean:AService 的bean对象
	beanName:"AService"
*/
@Override
public PropertyValues postProcessPropertyValues(
    PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {

    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        //调用inject()方法
        metadata.inject(bean, beanName, pvs);
    }
    //...
    return pvs;
}
//InjectionMetadata
public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
    Collection<InjectedElement> elementsToIterate =
        (this.checkedElements != null ? this.checkedElements : this.injectedElements);
    if (!elementsToIterate.isEmpty()) {
        boolean debug = logger.isDebugEnabled();
        for (InjectedElement element : elementsToIterate) {
            if (debug) {
                logger.debug("Processing injected element of bean '" + beanName + "': " + element);
            }
            //target:AService
            //beanName:AService
            element.inject(target, beanName, pvs);
        }
    }
}
//AutowiredAnnotationBeanPostProcessor,进行BService的bean初始化,并赋值给AService的属性
@Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
    //获取BService字段属性
    Field field = (Field) this.member;
    Object value;
    if (this.cached) {
        value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    else {
        DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
        desc.setContainingClass(bean.getClass());
        Set<String> autowiredBeanNames = new LinkedHashSet<String>(1);
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            //创建出BService的bean实例
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
        }

        //...省略

        if (value != null) {
            ReflectionUtils.makeAccessible(field);
            //将BService的bean赋值给AService的字段引用
            field.set(bean, value);
        }
    }
}
//具体beanFactory.resolveDependency()的方法往下
//DefaultListableBeanFactory
@Override
public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
                                Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

	//....
    else {
        Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
            descriptor, requestingBeanName);
        if (result == null) {
            //往下:
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return result;
    }
}
//DefaultListableBeanFactory
public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
                                  Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
      	//...
        return (instanceCandidate instanceof Class ?
                //resolveCandidate()
                descriptor.resolveCandidate(autowiredBeanName, type, this) : instanceCandidate);
    }
    finally {
        ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
    }
}
//DependencyDescriptor
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
			throws BeansException {
		//最后调用getBean()
    	//beanName:BService
    	//requiredType:class tools.BService
		return beanFactory.getBean(beanName, requiredType);
	}
//AbstractBeanFactory
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
   return doGetBean(name, requiredType, null, false);
}

最后调用AbstractBeanFactory.getBean()方法创建BService的bean,当创建完后在AutowiredAnnotationBeanPostProcessor.inject(Object bean, String beanName, PropertyValues pvs)方法后为AService的属性BService赋值;接下来就是创建BService的bean了

初始化BService

AbstractBeanFactory.getBean(),doGetBean(),注意这次是为BService创建bean

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

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

    // Eagerly check singleton cache for manually registered singletons.
	//从三级缓存中查询,首次初始化肯定不存在
    Object sharedInstance = getSingleton(beanName);

    //...不重要,省略

            // Create bean instance.
            //开始真正的创建bean
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        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);
            }

        
            //...省略后面的原型bean与非singleton 和 prototype的创建
    return (T) bean;
}
  • AbstractAutowireCapableBeanFactory.createBean().doCreateBean()
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {

    //...省略

    //doCreateBean:创建bean方法
   Object beanInstance = doCreateBean(beanName, mbdToUse, args);
   if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
   }
   return beanInstance;
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      throws BeanCreationException {

   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
	//从factoryBean中获取
    if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
    //为 null 代表不是factoryBean
   if (instanceWrapper == null) {
       //1、重点方法,创建bean实例,但不进行属性赋值与初始化,此时创建出BService的bean实例
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
    //BService 的bean
   final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
   Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
   mbd.resolvedTargetType = beanType;

    //...省略不重要的部分

    
    //开始解决循环依赖问题
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      if (logger.isDebugEnabled()) {
         logger.debug("Eagerly caching bean '" + beanName +
               "' to allow for resolving potential circular references");
      }
       
       //addSingletonFactory:将BService添加到三级缓存,并从二级缓存中移除(当前并不在于二级缓存)
       //当前AService也存在于三级缓存中
      addSingletonFactory(beanName, new ObjectFactory<Object>() {
         @Override
         public Object getObject() throws BeansException {
            return getEarlyBeanReference(beanName, mbd, bean);
         }
      });
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
       //属性赋值,包括了对循环依赖的解决
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
          //初始化方法包括 init、和beanPostProcessor回调
         exposedObject = initializeBean(beanName, exposedObject, mbd);
      }
   }

    //...暂时忽略后面代码
}
//对BService的AService属性进行赋值
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    // bean 实例的所有属性都在这里了
   PropertyValues pvs = mbd.getPropertyValues();

   if (bw == null) {
      if (!pvs.isEmpty()) {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      }
      else {
         // Skip property population phase for null instance.
         return;
      }
   }

	// 到这步的时候,bean 实例化完成(通过工厂方法或构造方法),但是还没开始属性设值,
   // InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改,
   // 我也没找到有实际的使用,所以我们暂且忽略这块吧
   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;
   }

   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

      // Add property values based on autowire by name if applicable.
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }

      // Add property values based on autowire by type if applicable.
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }

      pvs = newPvs;
   }

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

   if (hasInstAwareBpps || needsDepCheck) {
      PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      if (hasInstAwareBpps) {
         for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
               // 重点在这:注意这里会有个: AutowiredAnnotationBeanPostProcessor
               InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
               pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvs == null) {
                  return;
               }
            }
         }
      }
      if (needsDepCheck) {
         checkDependencies(beanName, mbd, filteredPds, pvs);
      }
   }

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

与AService的步骤一样,会通过 AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues() 获取bean,因为AService已经存在于第三级缓存中,所以可以获取到AService的bean实例

接下来就是通过AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues()为BService的属性AService赋了值,基本流程与AService一样,随后执行BService的初始化最后返回给AService的属性BService赋值

后续

随后在AbstractBeanFactory.doGetBean()方法中,创建完bean后,会调用getSingleton()方法

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

 		//...省略
    
            // Create bean instance.
            //开始真正的创建bean
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        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);
            }

        
            //...省略后面的原型bean与非singleton 和 prototype的创建
    return (T) bean;
}

getSingleton():将初始化的Bean放入到一级缓存,同时删除二级,三级缓存。

protected void addSingleton(String beanName, Object singletonObject) {
   synchronized (this.singletonObjects) {
      // 添加到一级缓存
      this.singletonObjects.put(beanName, singletonObject);
      // 移除二级缓存
      this.singletonFactories.remove(beanName);
      // 移除三级缓存
      this.earlySingletonObjects.remove(beanName);
      // 将完成的BeanName添加到已经注册的单例集合
      this.registeredSingletons.add(beanName);
   }
}

到此循环依赖完全打开。所以一级缓存中已经是完全创建好的单例Bean。

构造器的循环依赖

一般来说构造器的循环依赖是没办法解决的,但是spring为我们提供了延迟加载策略@lazy

通过延迟加载bean方式实现构造器的循环依赖

  • spring 的延迟加载策略:当有bean被定义为延迟加载(@lazyxml:lazy-initialization),BeanFactory容器中会有bean的定义信息BeanDefinition,但不会初始化bean,
  • 当有非延迟加载的bean引用了延迟bean,那么延迟策略就无效了,还是会加载立即到容器中
  • 但是当存在循环依赖的情况下呢?
  • 选择一个循环依赖的bean的构造器,使用@lazy注解,

测试代码

@Component("AService")
public class AService {
    BService bService;

    @Autowired
    public AService(@Lazy BService bService ) {
        this.bService = bService;
    }
}
@Component("BService")
public class BService {
    AService aService;

    @Autowired
    public BService(AService aService) {
        this.aService = aService;
    }
}

初始化 AService

初始化AService,情况大致与前面一致,不同处体现在实例化bean的方法中

  • AbstractAutowireCapableBeanFactory.createBeanInstance()
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
    // Make sure bean class is actually resolved at this point.
    //确保已经加载了此 class
    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());
    }

    //采用工厂方法实例化,factoryBean,此处未使用
    if (mbd.getFactoryMethodName() != null)  {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
     // 如果不是第一次创建,比如第二次创建 prototype 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);
        }
    }

    // Need to determine the constructor...
    //判断是否采用有参构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null ||
        mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
        mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
        // 构造函数依赖注入,此时AService的初始化是需要调用有参构造的
        //beanName:beanName
        //mbd:RootBeanDefinition,bean的描述信息
        //ctors:需要调用的构造函数
        //args:参数,第一次实例化bean所以args是null
        //往下:
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // No special handling: simply use no-arg constructor.
     // 调用无参构造函数
    return instantiateBean(beanName, mbd);
}
  • AbstractAutowireCapableBeanFactory.autowireConstructor()-->ConstructorResolver.autowireConstructor()
protected BeanWrapper autowireConstructor(
    String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs) {

    //bean需要使用注入构造方法来进行实例化时,会调用ConstructorResolver的autowireConstructor来进行实例化
    return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
//ConstructorResolver.autowireConstructor()
//...省略

在调用AService构造方法时,因为此时BService并没有初始化,无法注入BService,spring通过 CGLIB 动态代理生成了一个BService的子类,AService就注入了此子类

往后的属性赋值与初始化(populateBean()initializeBean())都不会存在循坏依赖情况,AService的bean就正常初始化完成,放入了一级缓存中

BService初始化

BService的初始化情况就相对简单明了了,BService通过构造函数创建,从一级缓存中取出AService注入即可

public class MainTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("tools");
        AService aService = context.getBean(AService.class);
        BService bService = context.getBean(BService.class);
        
        //false  true 证明不是同一个bean实例,只是继承于BService的子类
        System.out.println((aService.getbService()==bService)+"\t"+(aService.getbService() instanceof BService));
        //true
        System.out.println(aService.getbService().getaService() == aService);
        //true
        System.out.println(bService.getaService()==aService);

    }

}

总和上述,其实spring通过@lazy注解解决构造器循环依赖的方式就是通过动态代理生成子类再注入,并不注入依赖的父类型

这时又引出另外一个问题,明明AService里的是BService只是一个子类属性,里面并没有注入AService,那么为什么aService.getbService().getaService()又可以取回AService的bean实例?

  • 目前来看是通过 Cglib的动态代理调用,调回父类BService的getAService()方法