循环依赖
-
首先要清楚Spring中bean的注入方式有:构造方法注入、Setter注入、静态工厂注入,常用的主要是前两种
-
循环依赖指的是BeanA依赖于BeanB,BeanB依赖于BeanC,BeanC有依赖于BeanA,从而构成了一个环的情景。对应于bean的注入方式,也就有构造方法注入循环依赖,Setter注入循环依赖,静态工厂的不考虑。
-
对于bean的作用域通常又有单例和多例区分,因此,构造方法注入循环依赖又可以再分为单例构造方法注入循环依赖和多例构造方法循环依赖,Setter注入循环依赖分为单例setter注入循环依赖和多例setter注入循环依赖。
构造方法注入 | setter注入 |
---|---|
单例 | 单例 |
多例 | 多例 |
-
Spring中提供了对单例setter注入循环依赖的解决方案,构造方法注入场景单例,多例都不支持。这里需要详细讲述原理。
- 为什么无法解决构造方法注入循环依赖?
<!--单例构造方法--> <bean id="beanA" class="com.larry.circleCons.BeanA" scope="singleton"> <constructor-arg ref="beanB"/> </bean> <bean id="beanB" class="com.larry.circleCons.BeanB" scope="singleton"> <constructor-arg ref="beanC"/> </bean> <bean id="beanC" class="com.larry.circleCons.BeanC" scope="singleton"> <constructor-arg ref="beanA"/> </bean> 或者多例: <bean id="beanA" class="com.larry.circleCons.BeanA" scope="prototype"> <constructor-arg ref="beanB"/> </bean> <bean id="beanB" class="com.larry.circleCons.BeanB" scope="prototype"> <constructor-arg ref="beanC"/> </bean> <bean id="beanC" class="com.larry.circleCons.BeanC" scope="prototype"> <constructor-arg ref="beanA"/> </bean>
无论是单例还是多例,都会在通过getBean获取bean实例时,抛出异常,只不过由于单例默认有预加载机制,因此如果没有配置延迟加载那么将在Spring初始化过程中加载单例,抛出异常:
@org.junit.Test public void testCircleRef() { context = new ClassPathXmlApplicationContext("spring.xml"); context.getBean("beanA"); }
上述代码执行过程中,将抛出如下异常:
org.springframework.context.support.AbstractApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanA' defined in class path resource [spring.xml]: Cannot resolve reference to bean 'beanB' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanB' defined in class path resource [spring.xml]: Cannot resolve reference to bean 'beanC' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanC' defined in class path resource [spring.xml]: Cannot resolve reference to bean 'beanA' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanA': Requested bean is currently in creation: Is there an unresolvable circular reference?
那么Spring中,是如何检测构造方法注入循环依赖的呢?
Java中字段的初始化顺序是先静态字段,然后实例字段,然后才是构造方法,也就是说如果我们使用了构造方法注入来初始化实例对象,那么构造方法的入参对应的对象必须先于当前对象初始化完毕才行,如果是构造方法依赖注入:
public BeanA(BeanB beanB) {
super();
this.beanB = beanB;
}
public BeanB(BeanC beanC) {
super();
this.beanC = beanC;
}
public BeanC(BeanA beanA) {
super();
this.beanA = beanA;
}
实际上会形成这样的一种循环:
BeanA->BeanB-BeanC->BeanA,最终就是BeanA要先于BeanA初始化,形成了悖论,因此Spring无法解决这种循环依赖,抛出异常。
可以看下Spring构造方法注入,实例化bean时的调用栈:
从Spring的调用栈中可以很清晰的看到bean的初始化流程,也就是说BeanA的实例化之前,首先解析了构造参数入参的beanB,对BeanB的实例化又触发了对BeanC的实例化,直至最后检测到了循环。对于单例循环依赖使用了线程安全的ConcurrentHashMap。
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/**
* Callback before singleton creation.
* <p>The default implementation register the singleton as currently in creation.
* @param beanName the name of the singleton about to be created
* @see #isSingletonCurrentlyInCreation
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
对于prototype作用域的bean来说,原理类似,如下图所示:
只不过prototype使用了ThreadLocal来保存当前线程正在创建的bean名称,通过这个threadLocal来检测循环依赖:
/** Names of beans that are currently in creation. */
private final ThreadLocal<Object> prototypesCurrentlyInCreation =
new NamedThreadLocal<>("Prototype beans currently in creation");
/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread).
* @param beanName the name of the bean
*/
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
以上分析了Spring对单例和多例构造方法注入循环依赖的检测机制,我们可以做一个总结:
单例构造方法注入 | 多例构造方法注入 |
---|---|
对bean实例化,都需要先实例化构造方法参数的引用,这个流程是一样的 | |
都是在调用getBean()方法获取实例时触发依赖注入 | |
使用ConcurrentHashMap持有当前正在创建的bean | 使用ThreadLocal持有当前正在创建的bean |
我们也可以看到Spring采用了不同的缓存来持有单例和多例当前正在创建的bean。为什么Spring要采用不同的缓存呢?
作用域:单例的bean在整个Spring容器的生命周期只有一份,多例则是每次调用都会创建新的实例。Spring对单例的初始化有预初始化和延迟初始化两种,预初始化是随着Spring容器的初始化而初始化的,那么这里的线程是调用Spring容器的线程,而延迟初始化,指的是显示通过getBean()方法进行初始化,这里的线程就是调用getBean的线程,多个线程同时调用对于单例,为了保证其全局唯一,因此必须要用线程安全的容器来保证,对于多例,本来每次都会创建新的实例,因此它只要保证我当前线程调用能够看到自己的创建链就可以了,这正是ThreadLocal的最佳用武之地。
- Spring如何检测多例setter注入循环依赖?
<bean id="beanA" class="com.larry.circleCons.BeanA" scope="prototype">
<property name="beanB" ref="beanB"></property>
</bean>
<bean id="beanB" class="com.larry.circleCons.BeanB" scope="prototype">
<property name="beanC" ref="beanC"></property>
</bean>
<bean id="beanC" class="com.larry.circleCons.BeanC" scope="prototype">
<property name="beanA" ref="beanA"></property>
</bean>
从上图可以看出,setter注入和构造方法注入的依赖注入入口不一样,setter注入的入口是populateBean()方法,这里触发了依赖对象的实例化,而构造方法是autowireConstructor()方法。对于多例Spring其他地方的检测方法与构造方法检测是一样的。不再赘述。
- Spring如何解决单例setter注入循环依赖问题?
上图是单例setter注入,实例化的方法调用栈,可以看到单例setter注入的入口方法同多例一样仍然是populateBean()方法,调用流程实际上和多例的没有太大区别,但是当beanA调用栈又回到beanA时,Spring并没有报错,那么Spring怎么解决了单例setter注入的循环依赖问题?
在Sring org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])方法中存在这样一段代码
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
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));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
/**
* Add the given singleton factory for building the specified singleton
* if necessary.
* <p>To be called for eager registration of singletons, e.g. to be able to
* resolve circular references.
* @param beanName the name of the bean
* @param singletonFactory the factory for the singleton object
*/
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);
}
}
}
可以看到在调用polulateBean触发依赖注入对象的实例化之前,对于单例的bean,调用了addSingletonFactory()方法,我们从这个方法的注释中可以看到,它就是Spring解决单例setter注入的关键所在。也就是说在Spring完整依赖注入之前,已经将这个还未完成依赖注入的bean放到缓存singletonfactoryies里边了。这里出现了几个关键的点:
ObjectFactory
singletonObjects
singletonFactories
earlySingletonObjects
也就是说,我们理清楚了这个点之间的关系,单例setter注入循环依赖也就清楚了。
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
可以看到几个对象的类型,除了singletonObjects是线程安全的容器,其他两个都是普通的hashMap。根据上面的代码,**我们已经知道singletonFactories存放的是当前正在创建还未完成依赖注入的单例bean和它对应的ObjectFactory。
// Create bean instance.
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);
}
这里是创建单例作用域bean的入口,其中有几个关键方法getSingleton(beanName, ObjectFactory)和createBean()方法。
/**
* Return the (raw) singleton object registered under the given name,
* creating and registering a new one if none registered yet.
* @param beanName the name of the bean
* @param singletonFactory the ObjectFactory to lazily create the singleton
* with, if necessary
* @return the registered singleton object
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name 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 + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
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;
}
}
这里边看到了在try块中触发了对ObjectFactory的getObject()方法的回调,也就是说调用了createBean()方法。在createBean方法之中完成了对单例的创建,addSingletonFactory()方法的调用以及依赖注入对象的实例化,最后调用了addSingleton()方法,(到这里单例对象已经完成了实例化,是一个完全的对象)将beanName和已经实例化的对象关联放入缓存。
/**
* Add the given singleton object to the singleton cache of this factory.
* <p>To be called for eager registration of singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
可以看到addSingleton()方法就是对这几个缓存的处理。也就是说singletonObjects缓存了真正的单例。 也就是说缓存顺序是singletonFactories->singletonObjects,还有earlySingletonObjects的作用未知。在实例化创建对象的入口处首先调用getSingleton()方法。
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
@Override
@Nullable
public Object @Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
@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;
}(String beanName) {
return getSingleton(beanName, true);
}
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
@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;
}
可以看到getSingleton(beanName)又触发了对getSingleton(beanName, allowEarlyReference)的调用。这个方法就清晰的阐述了三个缓存之间的关系。
1)首先从singletonObjects这个实际存放已经创建好的单例的缓存中获取,如果没有获到,说明当前beanName对应的单例还在创建中或者是首次创建
2)于是到earlySingletonObjects中获取,如果获取到,则返回获取到的对象,如果没有获取到,则从singletonFactories中获取,如果获取到的singletonFactory为null,则表示这是首次创建单例,可以返回了,如果不为null,则表示,当前beanName的单例已经在创建中了,直接调用singletonFactory的getObject()方法获取对象,并将这个对象放入earlySingletonObjects中,如果又出现依赖注入触发了对同一个对象的调用,从earlySingletonObjects取出对象即可,不会再调用singletonFactory.getObject()。问题在于这个getObject()方法怎么获取到还未创建完成的那个单例对象呢?
第一次创建对象的调用getObject()触发了对createBean()的调用,第二次直接返回了创建的对象。怎么做到的?
首次创建bean的时候加入addSingletonFactory()方法是:
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
再次调用是从ObjectFactory方法中获取的,这时候调用的是
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
* @param beanName the name of the bean (for error handling purposes)
* @param mbd the merged bean definition for the bean
* @param bean the raw bean instance
* @return the object to expose as bean reference
*/
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;
}
getEarlyBeanReference()直接返回了原来已经创建的对象。