什么是循环依赖?
ServiceA依赖ServiceB,ServiceB依赖ServiceA。
启动Spring项目时,如果想实例化ServiceA,创建完ServiceA对象后,需要依赖注入ServiceB的对象,而ServiceB实例化时,需要ServiceA,如此反复,导致循环依赖。
@Service
public class ServiceA {
@Autowired
private ServiceB serviceB;
}
@Service
public class ServiceB {
@Autowired
private ServiceA serviceA;
}
#Spring如何解决循环依赖问题?
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry中有三个Map缓存了单例对象的信息
/** Cache of singleton objects: bean name to bean instance. */
//缓存的是已经创建完成,且完成依赖注入的单例对象(一级缓存)
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
//缓存的是对象工厂(三级缓存)
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
//缓存的是已经创建完成,但未完成依赖注入的单例对象(二级缓存)
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
- 一级缓存:缓存的是已经创建完成,且完成依赖注入的单例对象
- 二级缓存:缓存的是已经创建完成,但未完成依赖注入的单例对象
- 三级缓存:缓存的是对象工厂
大概步骤:
- 从缓存中获取ServiceA的对象实例,如果有则返回(第一次肯定没有),如果没有,则创建ServiceA对象实例。
- 创建ServiceA对象并放入缓存中、依赖注入ServiceB对象。
- 创建ServiceB对象实例并放入缓存中,依赖注入ServiceA对象。
- 从缓存中获取ServiceA对象,依赖注入到ServiceB中,ServiceB对象创建成功。
- 回到步骤2,ServiceA对象创建成功。
源码分析
随便建立个SpringBoot项目,在AbstractBeanFactory的Object getBean(String name) throws BeansException方法上打断点,因为主要观察ServiceA、ServiceB的实例化,因此打上条件断点name.equals(“serviceA”)||name.equals(“serviceB”),调试启动项目。
这就是调用链,可以看到代码是如何走到getBean方法的。
AbstractBeanFactory.doGetBean(
String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException
从一二三级缓存中获取ServiceA单例实例
第一次肯定获取不到。
如果是单例,从一级缓存中获取ServiceA的实例对象,取不到则调用createBean方法创建ServiceA实例
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!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();//会回调上面的createBean方法
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
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;
}
}
createBean方法如下
doCreateBean方法如下
-
首先实例化对象
-
如果一级缓存中没有该对象,会将实例的对象放入到三级缓存中,同时移除二级缓存。
-
然后依赖注入。这里ServiceA依赖ServiceB,因此又回到了AbstractBeanFactory.getBean方法来获取ServiceB。
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//返回的是一个BeanWrapper对象
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建bean对象
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//如果一级缓存中没有实例,将实例工厂放入到三级缓存中,并移除二级缓存
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//依赖注入
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
源码分析总结
上面代码的链路已经了解,做下总结。
1.1 首先获取ServiceA的实例AbstractBeanFactory.getBean(String name),name是"serviceA"
1.2 AbstractBeanFactory.doGetBean。
1.2.1 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton,从三级缓存中获取serviceA实例,未获取到。如果取到了直接返回。
1.2.2 如果是原型,直接调用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean方法,创建实例。
如果是单例,调用org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton方法获取单例
1.3 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton
1.3.1 从一级缓存中获取serviceA,未获取到。取到了则直接返回
1.3.2 未取到serviceA则通过singletonObject = singletonFactory.getObject()回调org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean方法创建实例
1.3.3 调用org.springframework.beans.factory.support.DefaultSingletonBeanRegistry方法,如果一级缓存中没有实例,则将实例工厂放入到三级缓存中,并将实例从二级缓存中移除
1.4 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean
1.4.1 调用doCreateBean方法
1.5 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
1.5.1 调用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance方法创建实例,并包装成BeanWrapper。
1.5.2 调用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean进行依赖注入,依赖注入时会获取serviceB实例,回到第一步。
1.5.3 调用org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.addSingletonFactory
流程图
如果A依赖B,且B依赖A。
- 首先getBean获取A实例,第一次创建缓存中都没有,会走到org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean方法创建Bean,创建完A实例对象,并且将A对象的工厂放入到三级缓存后,执行依赖注入B。
- 依赖注入B时需要获取B对象,缓存中没有,依然会走到org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean方法创建Bean,创建完B实例对象,并且将B对象的工厂放入到三级缓存后,执行依赖注入A。
- 这一步是解决循环依赖的重点,依赖注入A时需要获取A对象。三级缓存中有A对象工厂,根据工厂生成A对象并放入到二级缓存中(此时的A对象没有依赖注入B对象,A中存的B时null),且将一级三级缓存中的A对象移除。这里涉及到AOP,如果对象需要AOP,则根据工厂生成AOP的代理对象,这里不展开了。
- 依赖注入A对象成功后,B对象实例化成功,并将B对象缓存到一级缓存中,并将二三级缓存中的B对象移除。
- 回到A依赖注入B的步骤,将B注入A中,A对象实例化成功,并将A对象缓存到一级缓存中,并将二三级缓存中的A对象移除。
- A、B实例化完成后,只有一级缓存中存有完整的A、B对象,二三级缓存中没有A、B对象