spring处理循环依赖

看spring源代码时,发一段代码如下,不明白什么意思。百度一下,才有点弄明白,记录一下,。

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		//先从缓存中获取实例
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			//缓存中没有,并且当前创建的beanName正在加载
			synchronized (singletonObject) {
				singletonObject = this.earlySingletonObjects.get(beanName);
				//如果没有并且允许循环依赖创建
				if (singletonObject == null && allowEarlyReference) {
					//找到创建这个bean的工厂类,并创建这个bean.同时放到早期的缓存中,并移除这个创建工厂,不再创建
					ObjectFactory objectFactory = this.singletonFactories.get(beanName);
					if (objectFactory != null) {
						singletonObject = objectFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return (singletonObject != NULL_OBJECT) ? singletonObject : null;
	}

spring在处理循环依赖时,比如A-->B,B-->C,C-->A时。

1、构造方法上出现的依赖,一定抛出BeanCurrentlyInCreattionException异常。每次创建实例时都会在singletonsCurrentlyInCreation中缓存当前创建的beanName,如果发面创建的beanName存在,则抛出异常,A创建时singletonsCurrentlyInCreation中写A,但构造方法需要B实例,spring会去创建B时向singletonsCurrentlyInCreation写入B,但B又需要C,spring又会去创建C,向singletonsCurrentlyInCreation写入C的beanName,而C在创建时又需要A,此时再去创建A时,发现singletonsCurrentlyInCreation已经存在,抛出异常

protected void beforeSingletonCreation(String beanName) {
		if (!this.inCreationCheckExclusions.containsKey(beanName)
				&& this.singletonsCurrentlyInCreation.put(beanName, Boolean.TRUE) != null) {
			throw new BeanCurrentlyInCreationException(beanName);
		}
	}

2、通过set方法设置循环依赖时的处理,同样执行1)的步骤,当创建A时,使用默认参数构造函数创建成功后。会执行以下代码,创建一个earlyBeanReference写入singletonFactories中(beanName=A);之后执行setB时,创建B;同时也会执行写入一个singletonFactories中(beanName=B),之后去执行setC,创建C;当创建C实例时,同样的参数singletonFactories中(beanName=C),而执行C的setA方法,会去查找A实例,此时就用到了文章后开始的代码getSingle(A,true)。

if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, new ObjectFactory() {
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

3、getSingle(A, true)先去查询A的实例,因为A的实例还在创建中,所以会去查询A先创建的实例引用,这时也没查找到,再次去查询A的创建工厂,并取到A之前创建的实例的引用。同时缓存A实例的引用并删除A的创建工厂。同时返回A的实例的引用,执行C类的setA方法,C的bean创建成功。再依次执行B的setC方法和A的setB方法后。A和B的bean创建成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值