共计 9134 个字符,预计需要花费 23 分钟才能阅读完成。
关注“苏三说技术”,回复:开发手册、工夫治理 有惊喜。
兴许有些敌人对 spring 的循环依赖问题并不理解,让咱们先一起看看这个例子。
@Service
public class AService {
private BService bService;
public AService(BService bService) {this.bService = bService;}
public void doA() {System.out.println("call doA");
}
}
@Service
public class BService {
private AService aService;
public BService(AService aService) {this.aService = aService;}
public void doB() {System.out.println("call doB");
}
}
@RequestMapping("/test")
@RestController
public class TestController {
@Autowired
private AService aService;
@RequestMapping("/doSameThing")
public String doSameThing() {aService.doA();
return "success";
}
}
@SpringBootApplication
public class Application {
/**
* 程序入口
* @param args 程序输出参数
*/
public static void main(String[] args) {new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args);
}
}
咱们在运行 Application 类的 main 办法启动服务时,报了如下异样:
Requested bean is currently in creation: Is there an unresolvable circular reference?
这里提醒得很显著,呈现了循环依赖。
什么是循环依赖?
循环依赖是实例 a 依赖于实例 b,实例 b 又依赖于实例 a。
或者实例 a 依赖于实例 b,实例 b 依赖于实例 c,实例 c 又依赖于实例 a。
像这种多个实例之间的相互依赖关系形成一个环形,就是循环依赖。
为什么会造成循环依赖?
下面的例子中 AService 实例化时会调用构造方法 public AService(BService bService),该构造方法依赖于 BService 的实例。此时 BService 还没有实例化,须要调用构造方法 public BService(AService aService) 能力实现实例化,该构造方法偶合又须要 AService 的实例作为参数。因为 AService 和 BService 都没有提前实例化,在实例化过程中又相互依赖对方的实例作为参数,这样形成了一个死循环,所以最终都无奈再实例化了。
spring 要如何解决循环依赖?
只须要将下面的例子略微调整一下,不必构造函数注入,间接应用 Autowired 注入。
@Service
public class AService {
@Autowired
private BService bService;
public AService() {}
public void doA() {System.out.println("call doA");
}
}
@Service
public class BService {
@Autowired
private AService aService;
public BService() {}
public void doB() {System.out.println("call doB");
}
}
咱们看到能够失常启动了,阐明循环依赖被本人解决了
spring 为什么能循环依赖?
调用 applicationContext.getBean(xx) 办法,最终会调到 AbstractBeanFactory 类的 doGetBean 办法。因为该办法很长,我把局部不相干的代码省略掉了。
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {final String beanName = transformedBeanName(name); Object bean;
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
省略........
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
省略........
if (mbd.isSingleton()) {sharedInstance = getSingleton(beanName, () -> {
try {return createBean(beanName, mbd, args);
}
catch (BeansException ex) {destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {throw new IllegalStateException("No Scope registered for scope name'" + scopeName + "'");
}
try {Object scopedInstance = scope.get(beanName, () -> {beforePrototypeCreation(beanName);
try {return createBean(beanName, mbd, args);
}
finally {afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope'" + scopeName + "'is not active for the current thread; consider" +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
省略........
return (T) bean;
}
咱们能够看到,该办法一进来会调用 getSingleton 办法从缓存获取实例,如果获取不到。会判断作用域是否为:单例,多列 或者 都不是,不同的作用域创立实例的规定不一样。接下来,咱们重点看一下 getSingleton 办法。
public Object getSingleton(String beanName) {return getSingleton(beanName, true);
}
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;
}
咱们发现有三个 Map 汇合:
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name --> ObjectFactory */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name --> bean instance */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
singletonObjects 对应一级缓存,earlySingletonObjects 对应二级缓存,singletonFactories 对应三级缓存。
下面 getSingleton 办法的逻辑是:
- 先从 singletonObjects(一级缓存)中获取实例,如果能够获取到则间接返回 singletonObject 实例。
- 如果从 singletonObjects(一级缓存)中获取不对实例,再从 earlySingletonObjects(二级缓存)中获取实例,如果能够获取到则间接返回 singletonObject 实例。
- 如果从 earlySingletonObjects(二级缓存)中获取不对实例,则从 singletonFactories(三级缓存)中获取 singletonFactory,如果获取到则调用 getObject 办法创立实例,把创立好的实例放到 earlySingletonObjects(二级缓存)中,并且从 singletonFactories(三级缓存)删除 singletonFactory 实例,而后返回 singletonObject 实例。
- 如果从 singletonObjects、earlySingletonObjects 和 singletonFactories 中都获取不到实例,则 singletonObject 对象为空。
获取实例须要调用 applicationContext.getBean(“xxx”) 办法,第一次调用 getBean 办法,代码走到 getSingleton 办法时返回的 singletonObject 对象是空的。而后接着往下执行,默认状况下 bean 的作用域是单例的,接下来咱们重点看看这段代码:
createBean 办法会调用 doCreateBean 办法,该办法同样比拟长,咱们把不相干的代码省略掉。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper instanceWrapper = null;
省略......
if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
省略........
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {省略 .....}
省略 .......
return exposedObject;
}
该办法的次要流程是:
- 创立 bean 实例
- 判断作用域是否为单例,容许循环依赖,并且以后 bean 正在创立,还没有创立实现。如果都满足条件,则调用 addSingletonFactory 将 bean 实例放入缓存中。
- 调用 populateBean 办法进行依赖注入
- 调用 initializeBean 办法实现对象初始化和 AOP 加强
咱们关注的重点能够先放到 addSingletonFactory 办法上。
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);
}
}
}
该办法的逻辑是判断如果 singletonObjects(一级缓存)中找不到实例,则将 singletonFactory 实例放到 singletonFactories(三级缓存)中,并且移除 earlySingletonObjects(二级缓存)中的实例。
createBean 办法执行完之后,会调用外层的 getSingleton 办法
咱们重点看看这个 getSingleton 办法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction" +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {this.suppressedExceptions = new LinkedHashSet<>();
}
try {singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {throw ex;}
}
catch (BeanCreationException ex) {if (recordSuppressedExceptions) {for (Exception suppressedException : this.suppressedExceptions) {ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {if (recordSuppressedExceptions) {this.suppressedExceptions = null;}
afterSingletonCreation(beanName);
}
if (newSingleton) {addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
该办法逻辑很简略,就是先从 singletonObjects(一级缓存)中获取实例,如果获取不到,则调用 singletonFactory.getObject() 办法创立一个实例,而后调用 addSingleton 办法放入 singletonObjects 缓存中。
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);
}
}
该办法会将实例放入 singletonObjects(一级缓存),并且删除 singletonFactories(二级缓存),这样当前再调用 getBean 时,都能从 singletonObjects(一级缓存)中获取到实例了。
说了这么多,再回到示例中的场景。
spring 为什么要用三级缓存,而不是二级缓存?
像示例的这种状况只用二级缓存是没有问题的。
然而如果有这种状况:a 实例同时依赖于 b 实例和 c 实例,b 实例又依赖于 a 实例,c 实例也依赖于 a 实例。
a 实例化时,先提前裸露 objectFactorya 到三级缓存,调用 getBean(b) 依赖注入 b 实例。b 实例化之后,提前裸露 objectFactoryb 到三级缓存,调用 getBean(a) 依赖注入 a 实例,因为提前裸露了 objectFactorya,此时能够从三级缓存中获取到 a 实例,b 实例实现了依赖注入,降级为一级缓存。a 实例化再 getBean(c) 依赖注入 c 实例,c 实例化之后,提前裸露 objectFactoryc 到三级缓存,调用 getBean(a) 依赖注入 a 实例,因为提前裸露了 objectFactorya,此时能够从三级缓存中获取到 a 实例。留神这里又要从三级缓存中获取 a 实例,咱们晓得三级缓存中的实例是通过调用 singletonFactory.getObject() 办法获取的,返回后果每次都可能不一样。如果不必二级缓存,这里会有问题,两次获取的 a 实例不一样。
总结:
只有单例的状况下能力解决循环依赖问题,并且 allowCircularReferences 要设置成 true。
以下状况还是会呈现循环依赖:
- 结构器注入
- 作用域非单例的状况,当然在自定义作用域,本人能够实现防止循环依赖的逻辑
- allowCircularReferences 参数设置为 false
大家喜爱这篇文章的话,烦请关注一下:苏三说技术