spring解决循环依赖

之前面试有被问到过,面试官很调皮,我擅长的点没有问,然后抽了一个点让我回答,这个点考察了源码的理解,当时只是大概记得是提前暴露,但是细节答得有些粗糙,特补充一下,,,

	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缓存中取对象,如果对象不存在,但处于创建中,则加锁缓存,然后从提前暴露单例缓存中去拿对象,仍然无法取到则查看是否允许提前引用,如果允许,则从单例工厂缓存中获取单例工厂,然后从工厂中获取单例对象,然后将单例工厂从工厂缓存中移除。

posted @ 2019-07-20 23:01  再见,少年  Views(444)  Comments(0Edit  收藏  举报