什么是循环依赖
简单的说就是A依赖B,B依赖C,C依赖A这样就构成了循环依赖
循环依赖分为构造器依赖和属性依赖,众所周知的是Spring能够解决属性的循环依赖(set注入)。下文将从源码角度分析Spring是如何解决属性的循环依赖。
如下配置会产生循环依赖
@Test
public void testAbc() throws IOException {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
//获取bean的时候就会涉及到循环依赖的处理
Person person = (Person) bf.getBean("person");
person.say();
}
我们跟进源码可以看到如下代码
protected T doGetBean(
String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
//修正名称
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//从单例缓存中获取bean,这里就涉及到spring的1,2,3级缓存,第一次获取的时候sharedInstance 肯定为空
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 对于scope==prototype的,如果出现循环依赖,则直接抛异常,无法处理
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
......
if (!typeCheckOnly) {
//标记当前bean正在创建,就是将当前的beanName放到Set集合中,后面会作为其中一个判断条件去判断是否去从1或者2或者3级缓存中获取bean
markBeanAsCreated(beanName);
}
try {
......
// Create bean instance.
//创建bean实力的逻辑,
if (mbd.isSingleton()) {
//获取beanName的实力
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
......
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
......
return (T) bean;
查看public Object getSingleton(String beanName, ObjectFactory> singletonFactory)
如下
public Object getSingleton(String beanName, ObjectFactory> singletonFactory) {
synchronized (this.singletonObjects) {
//从一级缓存中获取bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
...
try {
/**
* 这里singletonFactory.getObject()实际是上一步中的匿名内部类的方法,即try中的语句块
* sharedInstance = getSingleton(beanName, () -> {
* try {
* return createBean(beanName, mbd, args);
* }...)
*/
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
...
return singletonObject;
}
}
我们可以继续返回上一步中继续查看return createBean(beanName, mbd, args);逻辑
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
...
try {
//这里是真正创建bean的逻辑,真正处理的逻辑一般都是doXXXX,do开头的
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
...
}
继续查看doCreateBean()
逻辑
这一步第一次将A放入了三级缓存,这个时候A实例化,但是未初始化。
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//这里最终会使用jdk的类加载器去去实例化当前bean,仅仅只是newInstance,
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class> beanType = instanceWrapper.getWrappedClass();
// ......
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
//缓存单例用于接续循环依赖,
//(单例 && 允许循环依赖(此处是恒定值,但是可以利用别的BeanFactory实现去改写这个值) && 当前bean是否处于正在创建中)
//这里为true,进入if,
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");
}
//添加到三级缓存,但是这时候bean还未实例化,下次别的Bean依赖的时候在调用真正的逻辑(匿名内部类)
//这里的匿名内部类意思是: 提前将实例化的bean暴露出去,记住,仅仅是实例化,没有初始化
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//填充属性,这个时候发现属性A类中的B属性未实例化,则实例化B,实例化B之后,则把把B的属性填充给A,这个时候填充
//的时候回从三级缓存中获取Bean
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
//......
return exposedObject;
}
继续查看填充属性的逻辑AbstractAutowireCapableBeanFactory.java
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
//......
//这里去发现当前bean需要填充的属性,也就是需要依赖的对象属性,这个时候如果pvc肯定不为空,继续进入下面if语句
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//......
if (pvs != null) {
//将依赖的属性赋值到当前bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
查看applyPropertyValues
AbstractAutowireCapableBeanFactory.java
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) {
return;
}
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
MutablePropertyValues mpvs = null;
List original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
//获取需要填充的属性名称s
original = mpvs.getPropertyValueList();
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
List deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
//循环去填充所有的属性值
for (PropertyValue pv : original) {
if (pv.isConverted()) {
deepCopy.add(pv);
}
else {
//依赖的属性名称
String propertyName = pv.getName();
//依赖的属性值,第一次这个值的类型是 RuntimeBeanReference
Object originalValue = pv.getValue();
//解析属性,里面的逻辑会进入RuntimeBeanReference判断逻辑,进行属性的解析
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// Set our (possibly massaged) deep copy.
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
继续查看valueResolver.resolveValueIfNecessary()
@Nullable
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
//上一步说的那个属性值是RuntimeBeanReference,这里判断一下为true,那就继续解析属性
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
//继续解析依赖的属性。
return resolveReference(argName, ref);
}
//...
继续查看resolveReference()方法可以看到准备在factory中解析依赖的bean
/**
* Resolve a reference to another bean in the factory.
* 在factory中解析对另一个bean的引用
*/
@Nullable
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
//...
}
else {
//这里会从factory中获取引用的bean,第一次循环完毕。里面会重头进入doGetBean()相关方法,然后一步步会获取引用的bean.
bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
}
//...
return bean;
}
//...
}
至此在初始化A的时候(只是实例化为初始化)的过程中,发现需要依赖B,那么这个时候再去factory中去找B,接下来我们发现B走了同样的流程,然后继续初始化A,此时状态如下:
程序实例化好所有的bean之后,第二轮开始进行依赖bean的set值,我们会看到刚开头的代码
protected T doGetBean(
String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
//修正名称
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//从单例缓存中获取bean,这里就涉及到spring的1,2,3级缓存
Object sharedInstance = getSingleton(beanName);
//...
继续查看getSingleton(beanName);
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
//第二轮进入的时候isSingletonCurrentlyInCreation(beanName)为true,进入if,每一次第一次初始化的bean的时候,都会
//标识此bean正在创建中。
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//从二级缓存获取,此时为null,allowEarlyReference默认一直true
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//从3级缓存获取之前存储的匿名内部类
ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//调用匿名内部类的方法去执行doCreateBean的创建
singletonObject = singletonFactory.getObject();
//将当前实例化好,但是未初始化的A放入二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
//把当前在三级缓存中存放的beanName移除掉
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
此时A,B在缓存中的状态为:
接着会将这个A会暴露出去,让B去完成A属性的赋值,这个时候我们可以继续查看初始化B的阶段中给A属性赋值的逻辑
@Nullable
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
//...
else {
//这个时候从factory中拿到了已经实例化好的A
bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
}
return bean;
//...
}
赋值操作
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
//...
//循环去填充所有的属性值
for (PropertyValue pv : original) {
//...
else {
//依赖的属性名称
String propertyName = pv.getName();
//依赖的属性值,第一次这个值的类型是 RuntimeBeanReference
Object originalValue = pv.getValue();
//解析属性,里面的逻辑会进入RuntimeBeanReference判断逻辑,进行属性的解析
//这个时候已经解析到A属性的Bean了,接下来就是把A 赋值给B bean即可完成B的实例化初始化
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
//...
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
//...
// Set our (possibly massaged) deep copy.
try {
//这里就是赋值操作
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
//...
}
一步步往下跟,我们可以看到如下代码
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
//将B放入一级缓存
this.singletonObjects.put(beanName, singletonObject);
//将B从三级缓存移除
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
此时A,B在1,2,3级缓存中的状态如下:
此时B已经完全的实例化并初始化完毕,可以正常的使用了。接下来就是继续完成A中B属性的赋值即可
剩下的逻辑我就不分析了。
A,B在1,2,3级缓存中的状态变化如下:
至此spring如何解决循环依赖已经分析完毕。但是我们需要思考以下几个问题
只有一级缓存能否解决循环依赖?
只有一级是解决不了的,一级缓冲中到时候存放的bean你是不知道到底是不是初始化完毕的。
只有二级能否解决循环依赖?
参考文章:https://www.bilibili.com/read/cv6674250