Spring源码-IOC容器(六)-bean的循环依赖

Spring IOC容器 源码解析系列,建议你们按顺序阅读,欢迎讨论java

(spring源码均为4.1.6.RELEASE版本)spring

  1. Spring源码-IOC容器(一)-构建简单IOC容器
  2. Spring源码-IOC容器(二)-Bean的定位解析注册
  3. Spring源码-IOC容器(三)-GetBean
  4. Spring源码-IOC容器(四)-FactoryBean
  5. Spring源码-IOC容器(五)-Bean的初始化
  6. Spring源码-IOC容器(六)-bean的循环依赖
  7. Spring源码-IOC容器(七)-ApplicationContext
  8. Spring源码-IOC容器(八)-NamespaceHandler与自定义xml
  9. Spring源码-IOC容器(九)-Component-Scan源码解析
  10. Spring源码-IOC容器(十)-@Autowired解析

不知道你们有没有想过这样一种状况,在Spring的配置中,存在两个bean A和bean B,A依赖于B,B依赖于A,即A和B相互依赖(引用),xml配置以下:缓存

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<bean id="beanA" class="com.lntea.spring.demo.bean.BeanA">
		<property name="beanB" ref="beanB"></property>
	</bean>
	
	<bean id="beanB" class="com.lntea.spring.demo.bean.BeanB">
		<property name="beanA" ref="beanA"></property>
	</bean>
	
</beans>

BeanA.java并发

package com.lntea.spring.demo.bean;

public class BeanA {

	private BeanB beanB;
	
	public void print(){
		System.out.println("beanB:" + beanB + " beanA:" + beanB.getBeanA());
	}

	public BeanB getBeanB() {
		return beanB;
	}

	public void setBeanB(BeanB beanB) {
		this.beanB = beanB;
	}
	
	
}

BeanB.javaide

package com.lntea.spring.demo.bean;

public class BeanB {

	private BeanA beanA;

	public BeanA getBeanA() {
		return beanA;
	}

	public void setBeanA(BeanA beanA) {
		this.beanA = beanA;
	}
	
	
}

此时经过BeanFactory获取beanA,并调用print方法this

BeanA beanA = beanFactory.getBean("beanA",BeanA.class);
beanA.print();

输出结果为spa

beanB:com.lntea.spring.demo.bean.BeanB@59a6e353 beanA:com.lntea.spring.demo.bean.BeanA@7a0ac6e3

能够看出beanA拿到了beanB的引用,beanB同时也拿到了beanA的引用。可见在Spring中是支持循环引用的,怎么实现的,有没有限制,咱们再从源码来解析一下。.net

getBean方法首先会从缓存中查询是否存在建立好的单例debug

Object sharedInstance = getSingleton(beanName);

public Object getSingleton(String beanName) {
	return getSingleton(beanName, true);
}

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	// 查询缓存中是否有建立好的单例
	Object singletonObject = this.singletonObjects.get(beanName);
	// 若是缓存不存在,判断是否正在建立中
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		// 加锁防止并发
		synchronized (this.singletonObjects) {
			// 从earlySingletonObjects中查询是否有early缓存
			singletonObject = this.earlySingletonObjects.get(beanName);
			// early缓存也不存在,且容许early引用
			if (singletonObject == null && allowEarlyReference) {
				// 从单例工厂Map里查询beanName
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
					// singletonFactory存在,则调用getObject方法拿到单例对象
					singletonObject = singletonFactory.getObject();
					// 将单例对象添加到early缓存中
					this.earlySingletonObjects.put(beanName, singletonObject);
					// 移除单例工厂中对应的singletonFactory
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return (singletonObject != NULL_OBJECT ? singletonObject : null);
}

从以上的代码能够看出code

  1. 只针对单例的bean,多例的后面讨论
  2. 默认的singletonObjects缓存不存在要get的beanName时,判断beanName是否正在建立中
  3. 从early缓存earlySingletonObjects中再查询,early缓存是用来缓存已实例化但未组装完成的bean
  4. 若是early缓存也不存在,从singletonFactories中查找是否有beanName对应的ObjectFactory对象工厂
  5. 若是对象工厂存在,则调用getObject方法拿到bean对象
  6. 将bean对象加入early缓存,并移除singletonFactories的对象工厂

上面最重要的就是singletonFactories什么时候放入了能够经过getObject得到bean对象的ObjectFactory。根据咱们的猜想,应该会是bean对象实例化后,而属性注入以前。仔细寻找后发现,在AbstractAutowireCapableBeanFactory类的doCreateBean方法,也就是实际bean建立的方法中,执行完createBeanInstance实例化bean以后有一段代码:

// bean为单例且容许循环引用且正在建立中
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并添加到singletonFactories中
	addSingletonFactory(beanName, new ObjectFactory<Object>() {
		[@Override](https://my.oschina.net/u/1162528)
		public Object getObject() throws BeansException {
			return getEarlyBeanReference(beanName, mbd, bean);
		}
	});
}


protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
	Assert.notNull(singletonFactory, "Singleton factory must not be null");
	synchronized (this.singletonObjects) {
		// 判断默认缓存中没有beanName
		if (!this.singletonObjects.containsKey(beanName)) {
			// 添加ObjectFactory到singletonFactories
			this.singletonFactories.put(beanName, singletonFactory);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.add(beanName);
		}
	}
}

当判断bean为单例且正在建立中,而Spring容许循环引用时,将能得到bean对象的引用的ObjectFactory添加到singletonFactories中,此时就与以前的getSingleton方法相呼应。而allowCircularReferences标识在spring中默认为true,可是也能够经过setAllowCircularReferences方法对AbstractAutowireCapableBeanFactory进行设置。

再来看下getObject方法中的getEarlyBeanReference方法。这里也设置了一个InstantiationAwareBeanPostProcessor后置处理器的扩展点,容许在对象返回以前修改甚至替换bean。

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
	Object exposedObject = bean;
	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 exposedObject;
				}
			}
		}
	}
	return exposedObject;
}

来梳理一下上面getBean("beanA")的执行过程

  1. 实例化BeanA
  2. 将能获取BeanA对象的ObjectFactory添加到singletonFactories中
  3. BeanA注入BeanB属性,调用getBean("beanB")方法
  4. 实例化BeanB
  5. 将能获取BeanB对象的ObjectFactory添加到singletonFactories中
  6. BeanB注入BeanA属性,调用getBean("beanA")
  7. 从singletonFactories中获取ObjectFactory并调用getObject方法拿到beanA对象的引用
  8. BeanB建立完成,注入到BeanA的beanB属性中
  9. BeanA建立完成返回

上面咱们了解了单例的bean循环引用的处理过程,那么多例的呢?其实咱们能够按上面的思路来思考一下,单例bean的循环引用是由于每一个对象都是固定的,只是提早暴露对象的引用,最终这个引用对应的对象是建立完成的。可是多例的状况下,每次getBean都会建立一个新的对象,那么应该引用哪个对象呢,这自己就已是矛盾的了。于是spring中对于多例之间相互引用是会提示错误的。

// 若是已经存在多例的对象在建立中,就会抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) {
	throw new BeanCurrentlyInCreationException(beanName);
}

Error creating bean with name 'beanA': Requested bean is currently in creation: Is there an unresolvable circular reference?

可见spring会认为多例之间的循环引用是没法解决的。

相关文章
相关标签/搜索