處理循環依賴問題

1. 循環依賴類別

1)構造參數依賴:無解app

2)屬性依賴:對多實例Bean無解,對單實例Bean採用earlySingletonExposure策略ide

     處理beanB依賴:ui

  createBean(beanA) -> addSingletonFactory(beanA) -> populateBean(beanA) -> autowireByName / autowireByTypethis

       ->spa

      getBean(beanB) -> createBean(beanB) -> populateBean(beanB) -> getBean(beanA) -> getSingleton(beanA)code

 

2. DefaultListableBeanFactory參考

1)createBean(beanA) --> doCreateBeanblog

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException {
    ...
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        ...
        addSingletonFactory(beanName, new ObjectFactory<Object>() {
            @Override
            public Object getObject() throws BeansException {
                return getEarlyBeanReference(beanName, mbd, bean);
            }
        });
    }

    Object exposedObject = bean;
    try {
 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) {
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
    }
    ...

    return exposedObject;
}

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
    ...
    synchronized (this.singletonObjects) {
        if (!this.singletonObjects.containsKey(beanName)) {
            this.singletonFactories.put(beanName, singletonFactory);  this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName);
        }
    }
}

 

2)getBean(beanA) --> doGetBeanrem

protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
    ...
 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) {
        ...
    }

    else {
        ...
    }

    return (T) bean;
}

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    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();
                    this.earlySingletonObjects.put(beanName, singletonObject);  this.singletonFactories.remove(beanName);                 }
            }
        }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
相關文章
相關標籤/搜索