摘要
本博文主要是分析spring中的循环依赖的产生与spring中解决循环依赖的方案。帮助大家更好的理解spring的源码。
一、spring 循环依赖的产生 DefaultSingletonBeanRegistry
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
/** Maximum number of suppressed exceptions to preserve. */
private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;
//spring一级缓存
/** Cache of singleton objects: bean name to bean instance. */
private final Map singletonObjects = new ConcurrentHashMap(256);
// spring三级缓存
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map singletonFactories = new HashMap(16);
// spring二级缓存
/** Cache of early singleton objects: bean name to bean instance. */
private final Map earlySingletonObjects = new ConcurrentHashMap(16);
………省略code
}
四、Spring缓存不能解决多例Bean的循环依赖问题
package com.zhuangxiaoyan.spring.srcode.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* @Classname BService
* @Description TODO
* @Date 2022/5/8 15:06
* @Created by xjl
*/
@Service
@Scope("prototype") // 多利模式
public class BService {
@Autowired
public AService aService;
public AService getaService() {
return aService;
}
public void setaService(AService aService){
this.aService=aService;
}
}
package com.zhuangxiaoyan.spring.srcode.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* @Classname AService
* @Description TODO
* @Date 2022/5/8 15:06
* @Created by xjl
*/
@Service
@Scope("prototype")// 多利模式
public class AService {
@Autowired
private BService bService;
public BService getbService() {
return bService;
}
public void setbService(BService bService) {
this.bService = bService;
}
public AService(){
System.out.println("设置为无参数构造函数……");
}
// 为A 比B 先设置呢?
}
循环依赖异常在spring的bean的配置的单例的是时候 spring 利用的三级缓存决绝了,但是spring的bean的是多例的时候,是没有办法解决循环依赖的问题。为什么在但是时候可以采用的三级缓存来实现呢?而多例的时候不行?因为在在多利的情况下注入的bean的对象是不明确的,所以spring不知道用哪一个生产的bean的对象。