spring針對Bean之間的循環(huán)依賴漱挚,有自己的處理方案。關(guān)鍵點(diǎn)就是三級緩存慨削。當(dāng)然這種方案不能解決所有的問題,他只能解決Bean單例模式下非構(gòu)造函數(shù)的循環(huán)依賴套媚。
我們就從A->B->C-A這個初始化順序缚态,也就是A的Bean中需要B的實例,B的Bean中需要C的實例堤瘤,C的Bean中需要A的實例玫芦,當(dāng)然這種需要不是構(gòu)造函數(shù)那種依賴。前提條件有了本辐,我們就可以開始了桥帆。毫無疑問,我們會先初始化A.初始化的方法是org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
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); //關(guān)注點(diǎn)1
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.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
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);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}
// Create bean instance.
if (mbd.isSingleton()) {
//關(guān)注點(diǎn)2
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@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);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
這個方法很長我們一點(diǎn)點(diǎn)說慎皱。先看我們的關(guān)注點(diǎn)1 Object sharedInstance = getSingleton(beanName)
根據(jù)名稱從單例的集合中獲取單例對象老虫,我們看下這個方法,他最終是org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)
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);
}
大家一定要注意這個方法,很關(guān)鍵茫多,我們開篇提到了三級緩存祈匙,使用點(diǎn)之一就是這里。到底是哪三級緩存呢地梨,第一級緩存singletonObjects
里面放置的是實例化好的單例對象菊卷。第二級earlySingletonObjects
里面存放的是提前曝光的單例對象(沒有完全裝配好)缔恳。第三級singletonFactories
里面存放的是要被實例化的對象的對象工廠宝剖。解釋好了三級緩存洁闰,我們再看看邏輯。第一次進(jìn)來this.singletonObjects.get(beanName)
返回的肯定是null万细。然后isSingletonCurrentlyInCreation
決定了能否進(jìn)入二級緩存中獲取數(shù)據(jù)扑眉。
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
從singletonsCurrentlyInCreation
這個Set中有沒有包含傳入的BeanName,前面沒有地方設(shè)置赖钞,所以肯定不包含腰素,所以這個方法返回false,后面的流程就不走了。getSingleton
這個方法返回的是null雪营。
下面我們看下關(guān)注點(diǎn)2.也是一個getSingleton
只不過他是真實的創(chuàng)建Bean的過程弓千,我們可以看到傳入了一個匿名的ObjectFactory的對象,他的getObject方法中調(diào)用的是createBean這個真正的創(chuàng)建Bean的方法献起。當(dāng)然我們可以先擱置一下洋访,繼續(xù)看我們的getSingleton
方法
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 the 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<Exception>();
}
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 != NULL_OBJECT ? singletonObject : null);
}
}
這個方法的第一句Object singletonObject = this.singletonObjects.get(beanName)
從一級緩存中取數(shù)據(jù),肯定是null谴餐。隨后就調(diào)用的beforeSingletonCreation
方法姻政。
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
其中就有往singletonsCurrentlyInCreation
這個Set中添加beanName的過程,這個Set很重要岂嗓,后面會用到汁展。隨后就是調(diào)用singletonFactory的getObject方法進(jìn)行真正的創(chuàng)建過程,下面我們看下剛剛上文提到的真正的創(chuàng)建的過程createBean
,它里面的核心邏輯是doCreateBean
.
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
//關(guān)注點(diǎn)3
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(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) {
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) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(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;
}
createBeanInstance
利用反射創(chuàng)建了對象厌殉,下面我們看看關(guān)注點(diǎn)3 earlySingletonExposure
屬性值的判斷食绿,其中有一個判斷點(diǎn)就是isSingletonCurrentlyInCreation(beanName)
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
發(fā)現(xiàn)使用的是singletonsCurrentlyInCreation這個Set,上文的步驟中已經(jīng)將BeanName已經(jīng)填充進(jìn)去了,所以可以查到公罕,所以earlySingletonExposure
這個屬性是結(jié)合其他的條件綜合判斷為true,進(jìn)行下面的流程addSingletonFactory
,這里是為這個Bean添加ObjectFactory,這個BeanName(A)對應(yīng)的對象工廠炫欺,他的getObject方法的實現(xiàn)是通過getEarlyBeanReference
這個方法實現(xiàn)的。首先我們看下addSingletonFactory的實現(xiàn)
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);
}
}
}
往第三級緩存singletonFactories存放數(shù)據(jù)熏兄,清除第二級緩存根據(jù)beanName的數(shù)據(jù)品洛。這里有個很重要的點(diǎn),是往三級緩存里面set了值摩桶,這是Spring處理循環(huán)依賴的核心點(diǎn)桥状。getEarlyBeanReference
這個方法是getObject的實現(xiàn),可以簡單認(rèn)為是返回了一個為填充完畢的A的對象實例硝清。設(shè)置完三級緩存后辅斟,就開始了填充A對象屬性的過程。下面這段描述,沒有源碼提示静檬,只是簡單的介紹一下。
填充A的時候我擂,發(fā)現(xiàn)需要B類型的Bean酵幕,于是繼續(xù)調(diào)用getBean方法創(chuàng)建扰藕,記性的流程和上面A的完全一致,然后到了填充C類型的Bean的過程芳撒,同樣的調(diào)用getBean(C)來執(zhí)行邓深,同樣到了填充屬性A的時候,調(diào)用了getBean(A),我們從這里繼續(xù)說笔刹,調(diào)用了doGetBean中的Object sharedInstance = getSingleton(beanName)
,相同的代碼芥备,但是處理邏輯完全不一樣了。
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);
}
還是從singletonObjects獲取對象獲取不到舌菜,因為A是在singletonsCurrentlyInCreation
這個Set中萌壳,所以進(jìn)入了下面的邏輯,從二級緩存earlySingletonObjects
中取日月,還是沒有查到袱瓮,然后從三級緩存singletonFactories
找到對應(yīng)的對象工廠調(diào)用getObject
方法獲取未完全填充完畢的A的實例對象,然后刪除三級緩存的數(shù)據(jù)山孔,填充二級緩存的數(shù)據(jù)懂讯,返回這個對象A。C依賴A的實例填充完畢了台颠,雖然這個A是不完整的褐望。不管怎么樣C式填充完了,就可以將C放到一級緩存singletonObjects
同時清理二級和三級緩存的數(shù)據(jù)串前。同樣的流程B依賴的C填充好了瘫里,B也就填充好了,同理A依賴的B填充好了荡碾,A也就填充好了谨读。Spring就是通過這種方式來解決循環(huán)引用的。