首页 > 应用开发 > Java > spring是如何解决循环依赖的
/** Cache of singleton objects: bean name –> bean instance */private final Map singletonObjects = new ConcurrentHashMap(256);/** Cache of singleton factories: bean name –> ObjectFactory */private final Map> singletonFactories = new HashMap>(16);/** Cache of early singleton objects: bean name –> bean instance */private final Map earlySingletonObjects = new HashMap(16);复制代码
protected Object getSingleton(String beanName, boolean allowEarlyReference) {Object singletonObject = this.singletonObjects.get(beanName);//isSingletonCurrentlyInCreation()判断当前单例bean是否正在创建中if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {synchronized (this.singletonObjects) {singletonObject = this.earlySingletonObjects.get(beanName);//allowEarlyReference 是否允许从singletonFactories中通过getObject拿到对象if (singletonObject == null && allowEarlyReference) {ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);if (singletonFactory != null) {singletonObject = singletonFactory.getObject();//从singletonFactories中移除,并放入earlySingletonObjects中。//其实也就是从三级缓存移动到了二级缓存this.earlySingletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);}}}}return (singletonObject != NULL_OBJECT ? singletonObject : null);}复制代码
public interface ObjectFactory<T> {T getObject() throws BeansException;}复制代码
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);}}}复制代码
版权声明:本文为「尚硅谷」的原创文章,转载请附上原文出处链接及本声明。下载相关视频学习资料到官方网站。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/27721058/viewspace-2851121/ ,如需转载,请注明出处,否则将追究法律责任。