【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)_公号:一条coding-优快云博客真没想到这题这么高频https://blog.youkuaiyun.com/skylibiao/article/details/119222944spring循环依赖解决了A依赖B,B依赖A,通过三级缓存机制实现循环依赖。
三级缓存用于存放成品和半成品的bean以及工厂,位于DefaultSingletonBeanRegistry类中
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
/** 一级bean缓存,有完整初始化的bean */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** 三级缓存,存放创建bean的beanFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** 二级缓存,存放早期的bean,循环依赖的bean还没有被完全初始化 */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** 已经注册的bean,所有的bean信息都在这里面,bean的创建和销毁也是操作里面的数据 */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
/** 把bean放入一级缓存,同时在二级,三级缓存销毁*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
/** 把beanFactory放入三级缓存 */
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);
}
}
}
/** 从缓存中获得bean,只能从1,2,3级其中之一获得 */
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
@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);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
/** 获得所有注册的bean的名字 */
@Override
public String[] getSingletonNames() {
synchronized (this.singletonObjects) {
return StringUtils.toStringArray(this.registeredSingletons);
}
}
/** 得到单例的bean数量 */
@Override
public int getSingletonCount() {
synchronized (this.singletonObjects) {
return this.registeredSingletons.size();
}
}
}
bean的获取过程及循环依赖的解决方案如下图
具体循环依赖解决方案可以见最上方链接