Spring 复习 3.循环依赖 3.1 定义
循环依赖指多个对象的创建过程中均需要注入对方对象,如下所示
class A{ B b; public A(){ } public A(B b){ this.b = b; } public void setB(B b){ this.b = b; } } class B{ A a; public B(){ } public B(A a){ this.a = a; } public void setA(A a){ this.a = a; } } 3.2 解决Spring中将对象创建分为如下两步
实例化:创建初始对象
初始化:注入属性
并且引入三级缓存,来提前暴露对象引用,从而解决循环依赖的问题
3.3 示例假设A和B的创建中,field均需要对方的引用,在refresh方法进行到finishBeanFactoryInitialization(beanFactory)时,会开始创建非懒加载的singleton,这里会先进入preInstantiateSingletons方法,根据beanName调用getBean方法,假设此时A先进行创建,那么会进入下面方法
doGetBeanorg.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
getSingleton---1
@Override @Nullable public Object getSingleton(String beanName) { return getSingleton(beanName, true); } @Nullable 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; }首先调用上面方法先从singletonObjects中场是获取,发现为null,由于isSingletonCurrentlyInCreation为false(对象未在创建过程中),因此直接返回null
if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { 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(beanName,ObjectFactory)方法简化版如下,传入的ObjectFactory实现类是一个lambda表达式,也即用createBean方法重写ObjectFactory#getObject方法
getSingleton---2
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { boolean newSingleton = false; try { singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { } } catch (BeanCreationException ex) { } finally { } if (newSingleton) { addSingleton(beanName, singletonObject); } } return singletonObject; } }这里第一行调用singletonFactory.getObject方法会触发createBean,又触发AbstractAutowireCapableBeanFactory#doCreateBean方法中主题步骤如下
实例化bean
将bean放入三级缓存singletonFactories
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }其中调用addSingletonFactory方法如下,此处传入的lambda表达式给定的即为ObjectFactory对象,在执行其getObject方法时,即执行getEarlyBeanReference方法(这里需要留意!)
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { if (!this.singletonObjects.containsKey(beanName)) { this.singletonFactories.put(beanName, singletonFactory); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); } } }
A执行populateBean,开始注入属性b,由于B的对象还未创建,getSingleton---1(b)为null,这时触发B对象创建
B进行实例化
B放入三级缓存
B执行populateBean,开始注入属性a,调用getSingleton---1方法获取a,发现一级缓存singletonObject中没有对应对象,且正在创建中,则从二级缓存earlySingletonObjects中获取,发现仍然为null且allowEarlyReference默认为true,则去三级缓存中去获取,最终从三级缓存中获取,由于放入三级缓存时,lambda表达式为() -> getEarlyBeanReference(beanName, mbd, bean),所以会调用getEarlyBeanReference方法如下
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); } } } return exposedObject; }