spring解决依赖循环

搭建源码调试环境

  • 安装gradle
  • github上下载spring-framework 源码,我下载的是spring-framework-4.3.13.RELEASE.zip
  • 解压到本地,执行根目录下的import-into-eclipse.bat 批处理文件,可以自动将整个项目生成为eclipse
    工程文件
  • 使用eclipse 打开工程根目录,可以发现所有spring 项目都导入了eclipse
  • 找到测试文件,打开spring-beans 工程,里面有一个src/test/java 的文件夹,里面有专门测试依赖循环的类org.springframework.beans.factory
    对应的bean 配置文件在src/test/resources 的FactoryBeanTest-circular.xml 文件中。

bean 配置文件和测试类

配置文件
   
      
   

   
      
   


类定义

BeanImpl1和BeanImpl2互相依赖,可以看到他们的类定义

public static class BeanImpl1 {

    private BeanImpl2 impl2;

    public BeanImpl2 getImpl2() {
      return impl2;
    }

    public void setImpl2(BeanImpl2 impl2) {
      this.impl2 = impl2;
    }
  }


  public static class BeanImpl2 {

    private BeanImpl1 impl1;

    public BeanImpl1 getImpl1() {
      return impl1;
    }

    public void setImpl1(BeanImpl1 impl1) {
      this.impl1 = impl1;
    }
  }

每个类有一个PassThroughFactoryBean工厂类,工厂类实现了FactoryBean和BeanFactoryAware接口,作用未知。

测试类

自定义了一个最简的测试类

  public void testMyCircularReferenceWithPostProcessor() {
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();  
    new XmlBeanDefinitionReader(factory).loadBeanDefinitions(MY_CIRCULAR_CONTEXT);
    CountingPostProcessor counter = new CountingPostProcessor();
    factory.addBeanPostProcessor(counter);

    BeanImpl1 impl1 = factory.getBean(BeanImpl1.class);
    System.out.println(impl1);
  }

调试过程

BeanImpl1 impl1 = factory.getBean(BeanImpl1.class)打上断点,跟踪发现进入了
org.springframework.beans.factory.support.DefaultListableBeanFactory类

  public  T getBean(Class requiredType) throws BeansException {
    return getBean(requiredType, (Object[]) null);
  }

//实际执行的方法
  public  T getBean(Class requiredType, Object... args) throws BeansException {
    //实际bean的创建是由resolveNameBean完成的
    NamedBeanHolder namedBean = resolveNamedBean(requiredType, args);
    if (namedBean != null) {
      return namedBean.getBeanInstance();
    }
    BeanFactory parent = getParentBeanFactory();
    if (parent != null) {
      return parent.getBean(requiredType, args);
    }
    throw new NoSuchBeanDefinitionException(requiredType);
  }

跟踪DefaultListableBeanFactory.resolveNamedBean(requiredType, args),requiredType=org.springframework.beans.factory.FactoryBeanTests$BeanImpl1,args=null。
该函数调用了DefaultListableBeanFactory.getBeanNamesForType(Class type),type=org.springframework.beans.factory.FactoryBeanTests$BeanImpl1
在其内部调用了DefaultListableBeanFactory.getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit)。
在其内部调用了AbstractBeanFactory.isTypeMatch(String name, ResolvableType typeToMatch),name=beanImpl1,
typeToMatch=org.springframework.beans.factory.FactoryBeanTests$BeanImpl1,其中AbstractBeanFactory是
DefaultListableBeanFactory的爷爷类
以上描述完,弯弯绕绕其实spring想干的是就是根据beanType去获取beanInstance,上面并不是主题。
在isTypeMatch函数中第一次调用到了DefaultSingletonBeanRegistry.getSingleton(String beanName, boolean allowEarlyReference)函数,这时beanImpl1还没有创建,现在只知道beanImpl1的beanName和beanType,也就是只知道xml配置中的内容。
现在的目标是创建一个benaImpl1。在初次调用getSingleton(String beanName, boolean allowEarlyReference)的时候
beanName=beanImpl1,allowEarlyReference=false。这里设置allowEarlyRefernce为false的原因是spring还什么都没干,
如果有人想在他创建完成之间引用他,是不被允许的。
查看源码

//这里尝试从缓存中获取singletonObject
  protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //singletonObjects这时候是空的
    Object singletonObject = this.singletonObjects.get(beanName);
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      synchronized (this.singletonObjects) {
        singletonObject = this.earlySingletonObjects.get(beanName);
        if (singletonObject == null && allowEarlyReference) {
          ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
          if (singletonFactory != null) {
            singletonObject = singletonFactory.getObject();
            //可以看到earlySingletonObjects的赋值条件是当这个bean的ObjectFactory已经注册到了
            //singletonFactories中,关于singletonFactories请看下方
            this.earlySingletonObjects.put(beanName, singletonObject);
            this.singletonFactories.remove(beanName);
          }
        }
      }
    }
    //最终返回null
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
  }

看到this.singletonObjects,查看定义发现在DefaultSingletonBeanRegistry类中定义了一系列需要用到的缓存内容。
这些在实现singleton,解决singleton循环依赖中是非常重要的,以下列出

/** Cache of singleton objects: bean name --> bean instance */
/*singleton对象缓存*/
  private final Map singletonObjects = new ConcurrentHashMap(256);

  /** Cache of singleton factories: bean name --> ObjectFactory */
  /*singleton工厂类缓存是解决依赖循环的关键,singleton工厂类作用以后会细说*/
  private final Map> singletonFactories = new HashMap>(16);

  /** 在创建中的singleton 类缓存,我本以为解决依赖循环一定用到他,后来发现他的使用是有条件的
   * 因为他还需要Object
   */
  private final Map earlySingletonObjects = new HashMap(16);

  /** Set of registered singletons, containing the bean names in registration order */
  private final Set registeredSingletons = new LinkedHashSet(256);

  /** Names of beans that are currently in creation */
  /*正在创建的bean类,这里只存储他们的beanName,不需要Object*/
  private final Set singletonsCurrentlyInCreation =
      Collections.newSetFromMap(new ConcurrentHashMap(16));

回到原来的地方,从缓存中获取singletonObject失败了,其中由于在检查beanName和beanType是否配对的时候,
需要遍历所有的bean定义,这里将调用到DefaultSingletonBeanRegistry.getSingleton(String beanName, boolean allowEarlyReference),其中beanName=beanImpl2,allowEarlyReference=false,不过依旧是返回null,缓存内容也没有变化。

在获取了和beanType对应的beanName之后,由于此处对应的beanName只有一个,会直接构建
NamedBeanHolder(beanName, getBean(beanName, requiredType, args))作为resolveNamedBean的返回结果。
注意这里调用了一个不同的getBean函数AbstractBeanFactory.getBean(String name, Class requiredType, Object... args)
是爷爷类AbstractBeanFactory中定义的函数,

  public  T getBean(String name, Class requiredType, Object... args) throws BeansException {
    return doGetBean(name, requiredType, args, false);
  }
  //实际干活的函数
  protected  T doGetBean(
      final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
      throws BeansException {

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

    // Eagerly check singleton cache for manually registered singletons.
    //立即检查缓存,这里返回null,但这个doGetBean函数里存在递归调用,以后就有货了
    Object sharedInstance = getSingleton(beanName);
    //无关代码
    ...
      
      //typeCheckOnly=false
      if (!typeCheckOnly) {
        //这个函数的作用:
        //AbstractBeanFactory有这样一个私有成员
        //private final Set alreadyCreated =
      //Collections.newSetFromMap(new ConcurrentHashMap(256));
      //注释是‘Names of beans that have already been created at least once’
      //这个函数的作用就是检查alreadyCreated是否有这个变量,如果没有则加入,
      //但此处bean还没有被创建,仅仅是访问到了。
      //可能与循环依赖有关,先进行注意。
        markBeanAsCreated(beanName);
      }

      try {
        //合并父bean定义
        final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        checkMergedBeanDefinition(mbd, beanName, args);

        // Guarantee initialization of beans that the current bean depends on.
        //由于我们此处没有设置depend-on属性,所以返回null
        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);
            getBean(dep);
          }
        }

        // Create bean instance.
       //创建bean instance
        if (mbd.isSingleton()) {
          //出现了新的getSingleton函数,这里有一个匿名内部类ObjectFactory,
         //其中createBean()方法可以根据名称判定是一个干活型的方法,现在这里进入getSingleton方法
          sharedInstance = getSingleton(beanName, new ObjectFactory() {
            @Override
            public Object getObject() throws BeansException {
              try {
                return createBean(beanName, mbd, args);
              }
              catch (BeansException ex) {
                // Explicitly remove instance from singleton cache: It might have been put there
                // eagerly by the creation process, to allow for circular reference resolution.
                // Also remove any beans that received a temporary reference to the bean.
                destroySingleton(beanName);
                throw ex;
              }
            }
          });
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
        }
       //无关操作
       ...
  }
 
 

DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory singletonFactory)方法,
注意到DefaultSingletonBeanRegistry中保存重要缓存singletonObjects,singletonFactories,earlySingletonObjects,registeredSingletons,singletonsCurrentlyInCreation。

  public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(beanName, "'beanName' must not be null");
    synchronized (this.singletonObjects) {
      Object singletonObject = this.singletonObjects.get(beanName);
      if (singletonObject == null) {
        if (this.singletonsCurrentlyInDestruction) {
          throw new BeanCreationNotAllowedException(beanName,
              "Singleton bean creation not allowed while singletons of this factory are in destruction " +
              "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
        }
        if (logger.isDebugEnabled()) {
          logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
        }

        //这里将beanImpl1加入了singletonsCurrentlyInCreation
        beforeSingletonCreation(beanName);
        boolean newSingleton = false;
        boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
        if (recordSuppressedExceptions) {
          this.suppressedExceptions = new LinkedHashSet();
        }
        try {
          //这里开始调用createBean去创建beanImpl1,这里可以往下看createBean的实现
          singletonObject = singletonFactory.getObject();
          newSingleton = true;
        }
        catch (IllegalStateException ex) {
          // Has the singleton object implicitly appeared in the meantime ->
          // if yes, proceed with it since the exception indicates that state.
          singletonObject = this.singletonObjects.get(beanName);
          if (singletonObject == null) {
            throw ex;
          }
        }
        catch (BeanCreationException ex) {
          if (recordSuppressedExceptions) {
            for (Exception suppressedException : this.suppressedExceptions) {
              ex.addRelatedCause(suppressedException);
            }
          }
          throw ex;
        }
        finally {
          if (recordSuppressedExceptions) {
            this.suppressedExceptions = null;
          }
          afterSingletonCreation(beanName);
        }
        if (newSingleton) {
          addSingleton(beanName, singletonObject);
        }
      }
      return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }
  }

AbstractAutowireCapableBeanFactory.createBean(String beanName, RootBeanDefinition mbd, Object[] args)
beanName=beanImpl1,mbd是合并父类定义后的beanImpl1的bean定义,args=null

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
    //一些无关代码
    ...
  //调用doCreateBean来创建beanINstance,下面跟踪远吗 
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
  }

AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args),beanName=beanImpl1, mbd是和合并父bean定义后的bean定义,源码如下:

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

    // Instantiate the bean.
    //BeanWrapper 是spring内部使用的beanInstance的包装类
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
      //factoryBeanInstanceCache是AbstractAutowireCapableBeanFactory内部定义的一个
      //ConcurrentHashMap(16)类型,用来存放未完成的FactoryBean instance的缓存,
      //但他此处与我们无关因为我们并没有使用Factory Bean
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
      //这一步是实际创建beanIstance的方,返回的BeanWrapper中就包含了benaInstance的引用,先到下方跟踪
      instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    //省略代码
    ...
  }  

AbstractAutowireCapableBeanFactory.createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args),其中beanName=beanImpl1,mbd是和父类合并后的beanImpl1的bean定义

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
     //无关代码
     ...
    // Need to determine the constructor...
    //找构造器,返回null,因为类定义中没有指定构造方法
    Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null ||
        mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
        mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
      return autowireConstructor(beanName, mbd, ctors, args);
    }

    // 直接来到了return,下面看instantiateBean方法
    return instantiateBean(beanName, mbd);
  }

AbstractAutowireCapableBeanFactory.instantiateBean(String beanName, RootBeanDefinition mbd),其中
beanName=beanImpl1,mbd是和父类合并后的beanImpl1的bean定义

  protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
      Object beanInstance;
      final BeanFactory parent = this;
      //没有设置SecurityManager
      if (System.getSecurityManager() != null) {
        beanInstance = AccessController.doPrivileged(new PrivilegedAction() {
          @Override
          public Object run() {
            return getInstantiationStrategy().instantiate(mbd, beanName, parent);
          }
        }, getAccessControlContext());
      }
      else {
        //来到了这里,先看getInstantiationStrategy返回的对象
        //按照名字来看是说spring为实例化制定了策略
        beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
      }
      BeanWrapper bw = new BeanWrapperImpl(beanInstance);
      initBeanWrapper(bw);
      return bw;
    }
    catch (Throwable ex) {
      throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
  }
 
 

AbstractAutowireCapableBeanFactory.getInstantiationStrategy()返回的是默认的实例化策略对象
CglibSubclassingInstantiationStrategy,这个类继承了SimpleInstantiationStrategy,实际是扩展了SimpleInstantiationStrategy
功能,我们此处用到的还是SimpleInstantiationStrategy中的instantiate方法,下面看源码:
SimpleInstantiationStrategy.instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)
其中bd是类合并后的beanImpl1的bean定义,beanName=beanImpl1,owner=AbstractAutowireCapableBeanFactory

  public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
    // Don't override the class with CGLIB if no overrides.
    if (bd.getMethodOverrides().isEmpty()) {
      Constructor constructorToUse;
      synchronized (bd.constructorArgumentLock) {
        //定义中没有构造器,也没有工厂方法
        constructorToUse = (Constructor) bd.resolvedConstructorOrFactoryMethod;
        if (constructorToUse == null) {
          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(new PrivilegedExceptionAction>() {
                @Override
                public Constructor run() throws Exception {
                  return clazz.getDeclaredConstructor((Class[]) null);
                }
              });
            }
            else {
              //得到了默认的构造器org.springframework.beans.factory.FactoryBeanTests$BeanImpl1()
              constructorToUse =  clazz.getDeclaredConstructor((Class[]) null);
            }
            bd.resolvedConstructorOrFactoryMethod = constructorToUse;
          }
          catch (Throwable ex) {
            throw new BeanInstantiationException(clazz, "No default constructor found", ex);
          }
        }
      }
      //这里进入
      return BeanUtils.instantiateClass(constructorToUse);
    }
    else {
      // Must generate CGLIB subclass.
      return instantiateWithMethodInjection(bd, beanName, owner);
    }
  }

BeanUtils.instantiateClass(Constructor ctor, Object... args),其中ctor是默认的BeanImpl1()

  public static  T instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException {
    //无关代码
    ...
    //这里利用默认构造器生成了新实例
    return ctor.newInstance(args);
    ...

有了生成的实例org.springframework.beans.factory.FactoryBeanTests$BeanImpl1@5bfa9431,这是他的impl2成员为null,函数返回
到AbstractAutowireCapableBeanFactory.instantiateBean(),继续执行

  protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
      //已执行代码
      ...      
      //这里返回了beanImpl1的实例
      beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
      //立刻创建一个包装类将实例包装
      BeanWrapper bw = new BeanWrapperImpl(beanInstance);
      //注意到initBeanWrapper是在BeanFactory 中定义的,跟踪发现并没有可疑操作
      initBeanWrapper(bw);
      return bw;
     ...

调用栈返回到AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)

  protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      throws BeanCreationException {
    //已执行部分
    ... 
    //返回一个包含beanImpl1,属性未填充的BeanWrapperImpl的引用
    instanceWrapper = createBeanInstance(beanName, mbd, args);
    //取出beanImpl1的引用
    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    mbd.resolvedTargetType = beanType;

    //无关代码
    ...

    // Eagerly cache singletons to be able to resolve circular references
    // 满足条件是singleton,允许循环依赖,并且isSingletonCurrentlyInCreation,会将这个属性设置为true
    //前两个没有问题,这个isSingletonCurrentlyInCreation在哪里判断呢
    //观察前面在DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory singletonFactory)中
    //第一次执行singletonFactory.getObject()之前,调用beforeSingletonCreation(beanName),将beanImpl1注册到了
    //singletonsCurrentlyInCreation中
    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");
      }
      //注意到这个新的ObjectFactory,与之前用来createBean()的工厂类不同,这也就是真正暴露的工厂方法,
      //这个工厂中记住了刚刚实例化的beanImp1的引用,也就是beanImpl2以后要获取的引用
      //将工厂方法加入缓存,这里进行跟踪
      addSingletonFactory(beanName, new ObjectFactory() {
        @Override
        public Object getObject() throws BeansException {
          return getEarlyBeanReference(beanName, mbd, bean);
        }
      });
    }

  //未执行代码
  ...
  }
 
 

DefaultSingletonBeanRegistry.addSingletonFactory(String beanName, ObjectFactory singletonFactory),其中beanName=beanImpl1,singletooFactory是上面返回getEarlyBeanReference方法的ObjectFactory

  protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    synchronized (this.singletonObjects) {
      if (!this.singletonObjects.containsKey(beanName)) {
        //将传入的ObjectFactory加入singletonFactories缓存
        this.singletonFactories.put(beanName, singletonFactory);
        //这个earlySingletonObjects一直是空
        this.earlySingletonObjects.remove(beanName);
        //按顺序存放已经注册的SingletonBean的名称,这里由空变为[beanImpl1]
        this.registeredSingletons.add(beanName);
      }
    }
  }

继续执行AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)

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

    //已执行代码
    ...
    if (earlySingletonExposure) {
      if (logger.isDebugEnabled()) {
        logger.debug("Eagerly caching bean '" + beanName +
            "' to allow for resolving potential circular references");
      }
      addSingletonFactory(beanName, new ObjectFactory() {
        @Override
        public Object getObject() throws BeansException {
          return getEarlyBeanReference(beanName, mbd, bean);
        }
      });
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
      //跟踪进入populateBean,这里开始要对beanImpl1的实例进行属性注入
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
        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);
      }
    }

    //未执行代码
    ...
 
 

AbstractAutowireCapableBeanFactory.populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw)
其中beanName=beanImpl1,mbd是合并父类定义后的beanImpl1的定义

  protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    //pvs中有propertyValueList,这里面就存储了所有属性
    //查看propertyValueList中的对象,发现了name=impl2,以及对应的RuntimeBeanReference对象
    //在依赖bean没有实例化的时候,BeanDefinition就是借助这个RuntimeBeanReference来表示这个被依赖的bean的
    //这些都是在读取xml的时候就已经完成的任务
    PropertyValues pvs = mbd.getPropertyValues();
    //无关代码
    ...
    //这个方法开始填充属性,跟踪
    applyPropertyValues(beanName, mbd, bw, pvs);
  }

AbstractAutowireCapableBeanFactory.applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs),其中beanName=beanImpl1,mbd是合并父类方法后的beanImpl1的定义,bw是包含
beanImpl1实例引用的BeanWrapperImpl,pvs里包含beanImpl1的属性

  protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    //无关代码
    ...
    //BeanDefinitionValueResolver 可以帮助将定义的属性RuntimeBeanReference解析成实例
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    List deepCopy = new ArrayList(original.size());
    boolean resolveNecessary = false;
    for (PropertyValue pv : original) {
      //第一个pv就是impl2属性
      if (pv.isConverted()) {
        deepCopy.add(pv);
      }
      else {
        //propertyName = impl2
        String propertyName = pv.getName();
        //impl2的RuntimeBeanReference
        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);
        }
        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));
        }
      }
    }
    //无关代码
    ...
  }

BeanDefinitionValueResolver.resolveValueIfNecessary(Object argName, Object value),
argName=impl2,value是impl2的RuntimeBeanReference

  public Object resolveValueIfNecessary(Object argName, 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);
    }
    //无关代码
    ...
  }

BeanDefinitionValueResolver.resolveReference(Object argName, RuntimeBeanReference ref),
argName=impl2,value是impl2的RuntimeBeanReference

  private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    //refName=beanImpl2
    String refName = ref.getBeanName();
    refName = String.valueOf(doEvaluate(refName));
    //无关代码
    ...
    //这里终于开始获取beanImpl2的bean,跟踪进入,
    //这里的beanFactory就是一直使用的DefaultListableBeanFactory
    Object bean = this.beanFactory.getBean(refName);
    this.beanFactory.registerDependentBean(refName, this.beanName);
    return bean;
    //无关代码
    ...
  }

AbstractBeanFactory.getBean(String name),name=beanImpl2

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

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

    // Eagerly check singleton cache for manually registered singletons.
    //尝试从缓存里取出bean实例,此时beanImpl2的流程与beanImpl1是相同的
    //只在属性填充的时候会有不同,我们的目的是找到beanImpl2是如何用ObjectFactory获得
    //beanImpl1的实例的。
    //这里返回null,缓存中获取不到
    Object sharedInstance = getSingleton(beanName);
 
   //无关代码
   ...
      if (!typeCheckOnly) {
        //AbstractBeanFactory.alreadyCreated加入beanImpl2
        //现在该set中拥有了[beanImpl1, beanImpl2]
        markBeanAsCreated(beanName);
      }

      try {
        //beanImpl2定义对象合并父类定义,这段主要就是用到mbd
        final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        checkMergedBeanDefinition(mbd, beanName, args);

        // Guarantee initialization of beans that the current bean depends on.
        //beanImpl2也没定义depend-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);
            getBean(dep);
          }
        }

        // Create bean instance.
        if (mbd.isSingleton()) {
          //这里产生了beanImpl2的ObjectFactory,跟踪进入getSingleton方法
          sharedInstance = getSingleton(beanName, new ObjectFactory() {
            @Override
            public Object getObject() throws BeansException {
              try {
                return createBean(beanName, mbd, args);
              }
              catch (BeansException ex) {
                // Explicitly remove instance from singleton cache: It might have been put there
                // eagerly by the creation process, to allow for circular reference resolution.
                // Also remove any beans that received a temporary reference to the bean.
                destroySingleton(beanName);
                throw ex;
              }
            }
          });
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
        }

     //无关代码
     ...
    return (T) bean;
  }
 
 

DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory singletonFactory)
beanName=beanImpl2, singletonFactory是用来创建beanImpl2的ObjectFactory

  public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(beanName, "'beanName' must not be null");
    synchronized (this.singletonObjects) {
      //这里singletonObjects仍是空
      Object singletonObject = this.singletonObjects.get(beanName);
      if (singletonObject == null) {
        if (this.singletonsCurrentlyInDestruction) {
          throw new BeanCreationNotAllowedException(beanName,
              "Singleton bean creation not allowed while singletons of this factory are in destruction " +
              "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
        }
        if (logger.isDebugEnabled()) {
          logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
        }
        //将beanImpl2加入singletonsCurrentlyInCreation缓存
        beforeSingletonCreation(beanName);
        boolean newSingleton = false;
        boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
        if (recordSuppressedExceptions) {
          this.suppressedExceptions = new LinkedHashSet();
        }
        try {
          //此处调用ObjectFactory中createBean来创建beanImpl2,跟踪进入
          singletonObject = singletonFactory.getObject();
          newSingleton = true;
        }
        catch (IllegalStateException ex) {
          // Has the singleton object implicitly appeared in the meantime ->
          // if yes, proceed with it since the exception indicates that state.
          singletonObject = this.singletonObjects.get(beanName);
          if (singletonObject == null) {
            throw ex;
          }
        }
        //未执行代码
        ...
  }

AbstractAutowireCapableBeanFactory.createBean(String beanName, RootBeanDefinition mbd, Object[] args),
其中beanName=beanImpl2,mbd是合并父类定义后的beanImpl2的bean定义,args=null

  protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
    //无关代码
    ...
    //跟踪方法
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
  }

AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)
其中beanName=beanImpl2,,mbd是合并父类定义后的beanImpl2的bean定义,args=null

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

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
      //beanImpl2实际在此处创建,跟踪
      instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    //未执行代码
    ...
  }

AbstractAutowireCapableBeanFactory.createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args)
其中beanName=beanImpl2,,mbd是合并父类定义后的beanImpl2的bean定义,args=null

  protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
     //无关代码
     ...
    // Need to determine the constructor...
    //找构造器,返回null,因为类定义中没有指定构造方法
    Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null ||
        mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
        mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
      return autowireConstructor(beanName, mbd, ctors, args);
    }

    // 直接来到了return,下面看instantiateBean方法
    return instantiateBean(beanName, mbd);
  }

AbstractAutowireCapableBeanFactory.instantiateBean(String beanName, RootBeanDefinition mbd),其中
beanName=beanImpl2,mbd是和父类合并后的beanImpl2的bean定义

  protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
     //无关代码
     ...
     //使用CglibSubclassingInstantiationStrategy去创建beanImpl2实例
      beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
      BeanWrapper bw = new BeanWrapperImpl(beanInstance);
      initBeanWrapper(bw);
      return bw;
    }
    catch (Throwable ex) {
      throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
  }

SimpleInstantiationStrategy.instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)
其中bd是类合并后的beanImpl2的bean定义,beanName=beanImpl2,owner=AbstractAutowireCapableBeanFactory

  public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
      //无关代码
      ...
      //一如beanImp1中,constructorToUse是默认的构造方法,跟踪
      return BeanUtils.instantiateClass(constructorToUse);
     //无关代码
     ...
  }

BeanUtils.instantiateClass(Constructor ctor, Object... args),其中ctor是默认的BeanImpl2()

  public static  T instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException {
    //无关代码
    ...
    //这里利用默认构造器生成了新实例
    return ctor.newInstance(args);
    ...

有了生成的实例org.springframework.beans.factory.FactoryBeanTests$BeanImpl1@5bfa9431,这是他的impl2成员为null,函数返回
到AbstractAutowireCapableBeanFactory.instantiateBean(),继续执行

  protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
      //已执行代码
      ...      
      //这里返回了beanImp2的实例
      beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
      //立刻创建一个包装类将实例包装
      BeanWrapper bw = new BeanWrapperImpl(beanInstance);
      //注意到initBeanWrapper是在BeanFactory 中定义的,跟踪发现并没有可疑操作
      initBeanWrapper(bw);
      return bw;
     ...

调用栈返回到AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)
beanName=beanImpl1,mbd是合并父类定义后的beanImpl1的定义

  protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      throws BeanCreationException {
    //已执行部分
    ... 
    //返回了一个包含beanImpl2,属性未填充的BeanWrapperImpl的引用
    instanceWrapper = createBeanInstance(beanName, mbd, args);
    //取出beanImpl2实例的引用
    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    mbd.resolvedTargetType = beanType;

    //无关代码
    ...

    //同beanImpl1,这里也是允许earlySingletonExposure
    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");
      }
      //将beanUImpl2用来解决依赖循环的ObjectFactory加入缓存
      //现在singletonFactories已经有了beanImpl1和beanImpl2的缓存,
      addSingletonFactory(beanName, new ObjectFactory() {
        @Override
        public Object getObject() throws BeansException {
          return getEarlyBeanReference(beanName, mbd, bean);
        }
      });
    }

  //未执行代码
  ...
  }
 
 

DefaultSingletonBeanRegistry.addSingletonFactory(String beanName, ObjectFactory singletonFactory),其中beanName=beanImpl2,singletooFactory是上面返回getEarlyBeanReference方法的ObjectFactory

  protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    synchronized (this.singletonObjects) {
      if (!this.singletonObjects.containsKey(beanName)) {
        //将传入的ObjectFactory加入singletonFactories缓存
        this.singletonFactories.put(beanName, singletonFactory);
        //这个earlySingletonObjects一直是空
        this.earlySingletonObjects.remove(beanName);
        //按顺序存放已经注册的SingletonBean的名称,这里由[beanImpl1]变为[beanImpl1,beanImpl2]
        this.registeredSingletons.add(beanName);
      }
    }
  }

继续执行AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)

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

    //已执行代码
    ...
    if (earlySingletonExposure) {
      if (logger.isDebugEnabled()) {
        logger.debug("Eagerly caching bean '" + beanName +
            "' to allow for resolving potential circular references");
      }
      addSingletonFactory(beanName, new ObjectFactory() {
        @Override
        public Object getObject() throws BeansException {
          return getEarlyBeanReference(beanName, mbd, bean);
        }
      });
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
      //跟踪进入populateBean,这里开始要对beanImpl2的实例进行属性注入,这里将会用到暴露的ObjectFactory
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
        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);
      }
    }

    //未执行代码
    ...
 
 

AbstractAutowireCapableBeanFactory.populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw)
其中beanName=beanImpl2,mbd是合并父类定义后的beanImpl2的定义

  protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    //获取beanImpl2属性
    PropertyValues pvs = mbd.getPropertyValues();
    //无关代码
    ...
    //这个方法开始填充属性,跟踪
    applyPropertyValues(beanName, mbd, bw, pvs);
  }

AbstractAutowireCapableBeanFactory.applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs),其中beanName=beanImpl2,mbd是合并父类方法后的beanImpl2的定义,bw是包含
beanImpl2实例引用的BeanWrapperImpl,pvs里包含beanImpl2的属性

  protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    //无关代码
    ...
    //BeanDefinitionValueResolver 可以帮助将定义的属性RuntimeBeanReference解析成实例
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    List deepCopy = new ArrayList(original.size());
    boolean resolveNecessary = false;
    for (PropertyValue pv : original) {
      //第一个pv就是impl1属性
      if (pv.isConverted()) {
        deepCopy.add(pv);
      }
      else {
        //propertyName = impl1
        String propertyName = pv.getName();
        //impl1的RuntimeBeanReference
        Object originalValue = pv.getValue();
        //跟踪进入这个方法
        Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
        
    //未执行代码
    ...
  }

BeanDefinitionValueResolver.resolveValueIfNecessary(Object argName, Object value),
argName=impl1,value是impl1的RuntimeBeanReference

  public Object resolveValueIfNecessary(Object argName, 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);
    }
    //无关代码
    ...
  }

BeanDefinitionValueResolver.resolveReference(Object argName, RuntimeBeanReference ref),
argName=impl1,value是impl1的RuntimeBeanReference

  private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    //refName=beanImpl2
    String refName = ref.getBeanName();
    refName = String.valueOf(doEvaluate(refName));
    //无关代码
    ...
    //通过这里获取beanImpl1的实例引用
    //注意到原来的beanImpl1就是通过这里来获取beanImpl2的,这里是调用栈的返回点
    Object bean = this.beanFactory.getBean(refName);
    this.beanFactory.registerDependentBean(refName, this.beanName);
    return bean;
    //无关代码
    ...
  }

AbstractBeanFactory.getBean(String name),name=beanImpl1

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

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

    //此时由于beanImpl1在创建的时候将ObjectFactory加入了singletonFactories,并且通过了
    //beforeSingletonCreation(beanName)将beanImpl1加入了singletonsCurrentlyInCreation
    //所以这里可以从缓存里拿出些东西了跟踪进入
    Object sharedInstance = getSingleton(beanName);
 
   //未执行代码
   ...
    return (T) bean;
  }

DefaultSingletonBeanRegistry.getSingleton(String beanName),beanName=beanImpl1

  public Object getSingleton(String beanName) {
    return getSingleton(beanName, true);
  }
  protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    Object singletonObject = this.singletonObjects.get(beanName);
    //由于singletonsCurrentlyInCreation中有beanImpl1,这里进入条件语句
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      synchronized (this.singletonObjects) {
        //earlySingletonObjects现在还是空,下面就会对他做出改变
        singletonObject = this.earlySingletonObjects.get(beanName);
        if (singletonObject == null && allowEarlyReference) {
          //这里获取到了beanImpl1暴露的ObjectFactory,回顾一下
          //addSingletonFactory(beanName, new ObjectFactory() {
          //@Override
          //public Object getObject() throws BeansException {
          // return getEarlyBeanReference(beanName, mbd, bean);
          // }
          //})
          //其中beanName=beanImpl1,mbd是beanImpl1定义,bean是当时刚刚创建beanImpl1实例的引用
          ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
          if (singletonFactory != null) {
            //这里会调用getEarlyBeanReference(beanName, mbd, bean)取出bean,跟踪进入
            //这里已经取到了想要的beanImpl1的引用
            singletonObject = singletonFactory.getObject();
            //这里可以看出earlySingletonObjects存的是些什么了
            //beanImpl1已经实例化,已经暴露了工厂方法,在他未完全创建完成并且有其他bean
            //想要从缓存中获取他时,会第一次调用到他的ObjectFactory中保存的实例引用
            //这时候会将他加入earlySingletonObjects这个map中,将他的实例引用直接保存到缓存中
            //保存的Object仍然可以通过这个getSingleton()函数获得,可见上方
            this.earlySingletonObjects.put(beanName, singletonObject);
            //丢弃工厂类,这也就告诉我们ObjectFactory只会使用一次,执行完其中的getEarlyBeanReference
            //函数对bean进行一些加工就完成使命了,下面跟踪getEarlyBeanReference看他对bean作了什么加工
            this.singletonFactories.remove(beanName);
          }
        }
      }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
  }
 
 

AbstractAutowireCapableBeanFactory.getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean)
其中beanName=beanImpl1,mbd是beanImpl1定义,bean是保存的beanImpl1的引用。在进入之前要记住这个函数只会调用一次

  protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    //检查是否有BeanPostProcessor 要做前置处理工作
    if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
          SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
          exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
          if (exposedObject == null) {
            return null;
          }
        }
      }
    }
    //这里由于没有定义BeanPostProcessor,返回bean
    return exposedObject;
  }

更多BeanPostProcessor
返回到doGetBean

  protected  T doGetBean(
      final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
      throws BeansException {
    
    final String beanName = transformedBeanName(name);
    Object bean;
    //成功从缓存中取到了beanImpl1的实例引用
    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的实例是FactoryBean时,会执行getObjectFromFactoryBean使用工厂类创建真正实例
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }
    else {
      //无关代码
      ...
    }

    //无关代码
    ...
    return (T) bean;
  }

  }

调用栈返回BeanDefinitionValueResolver.resolveReference(Object argName, RuntimeBeanReference ref)
其中argName=impl1, ref是beanImpl1的RuntimeBeanReference,这里是在为beanImpl2填充属性的过程中

  private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    try {
      //无关代码
      ...
      }
      else {
        //这里是返回点,返回了beanImpl1的引用
        Object bean = this.beanFactory.getBean(refName);
        //注册beanImpl2和beanImpl1的依赖关系,这里是beanImpl2依赖于beanImpl1
        this.beanFactory.registerDependentBean(refName, this.beanName);
        //返回
        return bean;
      }
    }
    catch (BeansException ex) {
      throw new BeanCreationException(
          this.beanDefinition.getResourceDescription(), this.beanName,
          "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
    }
  }

返回到调用栈BeanDefinitionValueResolver.resolveValueIfNecessary(Object argName, Object value)
中argName=impl1, value是beanImpl1的RuntimeBeanReference

  public Object resolveValueIfNecessary(Object argName, Object value) {
      //无关代码
      ...
      return resolveReference(argName, ref);
      //无关代码
      ...
  }

返回调用栈AbstractAutowireCapableBeanFactory.applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs)
其中beanName=beanImpl2,mbd是beanImpl2定义,bw是包含beanImpl2实例引用的BeanWrapperImpl,pvs是beanImpl2的属性列表

  protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    //无关代码
    ...
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    List 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();
        //返回点,解析Value成功
        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();
    }
    try {
      //利用反射调用对应的set方法设置属性
      bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    }
    catch (BeansException ex) {
      throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
  }

可以看到applyPropertyValues将属性都设置了值,
方法结束返回到AbstractAutowireCapableBeanFactory.populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw)
beanName=beanImpl2,mbd是beanImpl2的定义,bw是包含beanImpl2实例引用的BeanWrapperImpl
方法结束返回AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)
其中beanName=beanImpl2,mbd是beanImpl2的定义,接下来要完成创建beanImpl2最后的一些工作

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

    // 已执行代码
    // 这里完成了instanceWrapper = createBeanInstance
    //以及addSingletonFactory
    ...
    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
      //完成了beanImpl2的属性设置,成功填充了未完成的beanImpl1
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
        //执行init()方法,还有前置的BeanPostProcessors,这里并没有定义
        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) {
      //这里调用getSingleton函数的目的是从earlySingletonObjects中取出对象
      Object earlySingletonReference = getSingleton(beanName, false);
      if (earlySingletonReference != null) {
        if (exposedObject == bean) {
          exposedObject = earlySingletonReference;
        }
        else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
          String[] dependentBeans = getDependentBeans(beanName);
          Set 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;
  }

DefaultSingletonBeanRegistry.getSingleton(String beanName, boolean allowEarlyReference)
beanName=beanImpl2,allowEarlyReference=false

  protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //这里的目的不是已经创建好的singletonObject
    Object singletonObject = this.singletonObjects.get(beanName);
    //看一下缓存现在的状态
    //singletonObjects=[]
    //singletonsCurrentlyInCreation=[beanImpl1,beanImpl2]
    //earlySingletonObjects含有["beanImpl1":beanImpl1实例引用]
    //registeredSingletons=[beanImpl1,beanImpl2]
    //singletonFactories只有beanImpl2的ObjectFactory
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      synchronized (this.singletonObjects) {
        //这里的唯一目的就是从earlySingletonObjects中获取对象,
        //也即那些未完成创建,单被其他类提前引用,已经完成了前置PostProcessor方法的bean实例
        //这里为null, 因为还没有类调用过beanImpl2暴露的工厂中的getEarlyBeanReference的方法。
        singletonObject = this.earlySingletonObjects.get(beanName);
        //这段代码是不会进入的,因为allowEarlyReference=false
        if (singletonObject == null && allowEarlyReference) {
          ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
          if (singletonFactory != null) {
            singletonObject = singletonFactory.getObject();
            this.earlySingletonObjects.put(beanName, singletonObject);
            this.singletonFactories.remove(beanName);
          }
        }
      }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
  }

返回AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)
其中beanName=beanImpl2,mbd是beanImpl2的定义

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

    // 已执行代码
    // 这里完成了instanceWrapper = createBeanInstance
    //以及addSingletonFactory
    //populateBean进行属性填充
    //initializeBean进行init和前置PostProcessor执行
    ...

    if (earlySingletonExposure) {
      //这里调用getSingleton函数是为了从earlysingletonObjects中取得对象,这里返回null
      Object earlySingletonReference = getSingleton(beanName, false);
      if (earlySingletonReference != null) {
        if (exposedObject == bean) {
          exposedObject = earlySingletonReference;
        }
        else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
          String[] dependentBeans = getDependentBeans(beanName);
          Set 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.");
          }
        }
      }
    }
    //无关代码
    ...
    //返回创建完成的beanImpl2
    return exposedObject;
  }
  返回调用栈createBean(String beanName, RootBeanDefinition mbd, Object[] args) 
  ```java
    protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
    //无关代码
    ...
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    //无关代码
    ...
    return beanInstance;
  }

返回调用栈DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory singletonFactory)
beanName=beanImpl2,singletonFactory是beanImpl2带有createBean的ObjectFactory

  public Object getSingleton(String beanName, ObjectFactory singletonFactory) {

    synchronized (this.singletonObjects) {
        //尝试从singletonObjects中获得singletonObject
        //将beanImpl2加入singletonsCurrentlyInCreation
        ...
        try {
          //执行了createBean之后返回创建好的beanImpl2
          singletonObject = singletonFactory.getObject();
          //新创建singleton的标记
          newSingleton = true;
        }
        catch (IllegalStateException ex) {
          // Has the singleton object implicitly appeared in the meantime ->
          // if yes, proceed with it since the exception indicates that state.
          singletonObject = this.singletonObjects.get(beanName);
          if (singletonObject == null) {
            throw ex;
          }
        }
        catch (BeanCreationException ex) {
          if (recordSuppressedExceptions) {
            for (Exception suppressedException : this.suppressedExceptions) {
              ex.addRelatedCause(suppressedException);
            }
          }
          throw ex;
        }
        finally {
          if (recordSuppressedExceptions) {
            this.suppressedExceptions = null;
          }
          //在创建完成后,将beanImpl2从singletonsCurrentlyInCreation抹除beanImpl2
          afterSingletonCreation(beanName);
        }
        if (newSingleton) {
          //第一次创建的singleton,加入singletonObjects缓存
          addSingleton(beanName, singletonObject);
        }
      }
      return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }
  }

返回调用栈AbstractBeanFactory.doGetBean(String name, Class requiredType, Object[] args, boolean typeCheckOnly)
其中name=beanImpl2

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

    //调用getSinleton(beanImpl2)尝试缓存取得beanImpl2
    ...
        // Create bean instance.
        if (mbd.isSingleton()) {
          //调用栈返回点,取得了beanImpl2创建好的实例
          sharedInstance = getSingleton(beanName, new ObjectFactory() {
            @Override
            public Object getObject() throws BeansException {
              try {
                return createBean(beanName, mbd, args);
              }
              catch (BeansException ex) {
                // Explicitly remove instance from singleton cache: It might have been put there
                // eagerly by the creation process, to allow for circular reference resolution.
                // Also remove any beans that received a temporary reference to the bean.
                destroySingleton(beanName);
                throw ex;
              }
            }
          });
          //检查是不是FactoryBean,如果是调用工厂方法创建bean
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
        }
        //无关代码
        ...

    // 类型转换工作
    ...
    return (T) bean;
  }
 
 

调用栈返回BeanDefinitionValueResolver.resolveReference(Object argName, RuntimeBeanReference ref)
argName=impl2,value是impl2的RuntimeBeanReference

  private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    try {
      String refName = ref.getBeanName();
      refName = String.valueOf(doEvaluate(refName));
      //无关代码
      ...
      }
      else {
        //bean现在是beanImpl的实例引用
        Object bean = this.beanFactory.getBean(refName);
        //注册beanImpl1和beanImpl2的依赖关系,这里是beanImpl1依赖于beanImpl2
        this.beanFactory.registerDependentBean(refName, this.beanName);
        //返回
        return bean;
      }
    }
    catch (BeansException ex) {
      throw new BeanCreationException(
          this.beanDefinition.getResourceDescription(), this.beanName,
          "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
    }
  }

调用栈返回,beanImpl1的属性也设置完成了applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs),beanName=beanImpl1

  protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
   //无关代码
   ...
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    List deepCopy = new ArrayList(original.size());
    for (PropertyValue pv : original) {
      //...
      String propertyName = pv.getName();
      Object originalValue = pv.getValue();
      //返回点,beanImpl1的属性解析完成
      Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
      //属性类型转换等加工
      ...
    }
    ...
    //利用反射set函数设置属性
    bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    ...
  }

调用栈返回AbstractAutowireCapableBeanFactory.doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)
,再一次见到了创建bean的主体函数,其中beanName=beanIml1

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

    // 已执行代码
    // 这里完成了instanceWrapper = createBeanInstance
    //以及addSingletonFactory
    ...
    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
      //完成了beanImpl1的属性设置
      populateBean(beanName, mbd, instanceWrapper);
      if (exposedObject != null) {
        //执行init()方法,还有前置的BeanPostProcessors,这里并没有定义
        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) {
      //这里调用getSingleton函数成功从缓存中取得了earlySingletonObjects里的beanImpl1未完成的实例对象
      Object earlySingletonReference = getSingleton(beanName, false);
      if (earlySingletonReference != null) {
        //exposedObject,bean和这里的earlySingletonReference分别记录了bean在创建过程的三个阶段
        //bean代表实例刚刚创建,还没有设置
        //exposedObject代表已经设置了属性,执行了init方法,和postprocessor的bean实例
        //earlySingletonReference代表已经执行了postprocessor的bean实例
        if (exposedObject == bean) {
          //这里是因为依赖这个对象的其他对象获取到的是earlySingletonReference,不能欺诈
          exposedObject = earlySingletonReference;
        }
        else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
          String[] dependentBeans = getDependentBeans(beanName);
          Set 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 {
      //注册bean为可任意处理的bean
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
      throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
    //返回
    return exposedObject;
  }

之后做的事情,就和beanImpl2在创建完成后做的一样,从singletonsCurrentlyInCreation缓存中将beanImpl1移除,将beanImpl1加入
singletonObjects缓存。经过漫长的调用栈,至此两个互相依赖的类就都创建完成了。

总结如何实现依赖循环

利用缓存
   BeanFactory{
      Map singletonObjects;
      Map> singletonFactories;
      Map earlySingletonObjects;
      Set singletonsCurrentlyInCreation;
   }
主要函数
   BeanFactory{
      Object getSingleton(String beanName, boolean allowEarlyReference);
      Object getSingleton(String beanName, ObjectFactory singletonFactory);
      T doGetBean(String name, Class requiredType, Object[] args, boolean typeCheckOnly);
      Object createBean(String beanName, RootBeanDefinition mbd, Object[] args);
      Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args);
      void populateBean(beanName, mbd, instanceWrapper);
   }
两种ObjectFactory
   BeanFactory{
      ObjectFactory() {...return createBean(beanName, mbd, args)};
      ObjectFactory() {...return getEarlyBeanReference(beanName, mbd, bean)};
   }
 
 
解决思路

给出伪代码

   getSingleton(beanName){
     //优先从singletonObjects中获取,查找已创建对象,若取得则返回
     //从earlySingletonObjects中获取,查找创建中已暴露的对象(已经执行了暴露工厂方法的对象),若取得则返回
     // 尝试利用singletonFactories中工厂取得提前创建的对象,若成功,将该工厂从singletonFactories中删除,
     //并将取得的对象加入earlySingletonObjects,返回取得的对象
     //若缓存中没有获取到对象,说明是新创建的singleton
     //创建bean之前,将beanName加入singletonsCurrentlyInCreation
     //创建bean,调用createSingleton(beanName)
     //singletonsCurrentlyInCreation中移除beanName
     //返回引用
   }
   createSingleton(beanName){
     //实例化对象,使用bean变量记录引用
     //建立一个匿名内部类ObjectFactory记录当前的bean,并将返回提前暴露的对象
     //将该ObjectFactory加入singletonFactories
     //填充属性,属性中若有依赖bean则调用getSingleton(beanName),执行初始化,使用exposedObject记录引用
     //检查earlySingletonObjects,尝试从中取得bean对象,用earlySingletonExposure记录
     //返回引用,优先级earlySingletoNObjects>singletonObjects>bean
   }

你可能感兴趣的:(spring解决依赖循环)