봄 5.x를 소스 여행 서른 넷의 getBean 순환 종속성 솔루션

봄 5.x를 소스 여행 서른 넷의 getBean는 순환 종속성 하나의 사건을 해결

순환 종속성 흐름도 용액

순환 종속성에서 봐는, 라이트를 해결하는 방법의 흐름도이다 :

그림 삽입 설명 여기

솔루션

간단히 말해서, 객체의 첫 번째 인스턴스가되는 A컬렉션에 저장 한 다음 속성을 입력하고, 자신의 종속 개체의 예는 B종속 객체가있는 경우, B또한 의존 A발견이 시간에 컬렉션의 인스턴스에,이 경우 A이 발견 A밖으로 걸릴 것입니다 , 줄 B전체에 충전 성, 후 B를하고 B도 가득 A뿐만 아니라 전체. 사실, 원리는 매우 간단 다른 종속을 피하기 위해 넣어 장소를 찾는 것입니다, 그들에 의존 꺼내왔다.
그림 삽입 설명 여기

주요 방법 중 일부

인스턴스를 만든 후이 방법은 당신이 원하는, 즉, 호출됩니다 ObjectFactory에 저장 singletonFactories수집, 다음 호출을 꺼낼 수있다 getObject인스턴스를 얻을 수 있습니다.

	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);//添加到已注册
			}
		}
	}

ObjectFactory그것은 기록 된 lambda표현.
그림 삽입 설명 여기

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;
	}

getSingleton

여기서 키가 생성되는 경우가 될 수 있고, 순환 참조를 해결하기위한 ObjectFactory취득 호출 getObject방법은 그들에 의존하는 오브젝트의 앞 얻을 수있다. A넣어 만든 singletonFactories의지에 B, B작성하고 다음에 의존 A, A로부터 얻을 수있는이 시간 시간 수 singletonFactories에 도착하고 해결 순환 의존성으로 채워진다에 의존하고 있습니다.

@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);//从singletonFactories获取出来,放进去
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return singletonObject;
	}

음, 오늘, 우리는 단지 자신의 학습, 제한 용량 이해를 참조하십시오 위대한 하나님을 뿌리지 마십시오 도움이 연구에 희망과 이해, 용서하십시오.

게시 된 235 개 원래 기사 · 원 찬양 74 ·은 30000 +를 볼

추천

출처blog.csdn.net/wangwei19871103/article/details/105165501