[读书笔记]Spring中的循环依赖详解

什么是循环依赖?

循环依赖就是N个类中循环嵌套引用,如果在日常开发中我们用new 对象的方式发生这种循环依赖的话程序会在运行时一直循环调用,直至内存溢出报错。

那么Spring是如何解决循环依赖的?

【1】Spring循环依赖的三种方式

① 构造器参数循环依赖

Spring容器会将每一个正在创建的Bean 标识符放在一个“当前创建Bean池”中,Bean标识符在创建过程中将一直保持在这个池中,因此如果在创建Bean过程中发现自己已经在“当前创建Bean池”里时将抛出BeanCurrentlyInCreationException异常表示循环依赖。而对于创建完毕的Bean将从“当前创建Bean池”中清除掉。

首先我们先初始化三个Bean。

public class StudentA {
	private StudentB studentB ;
	public void setStudentB(StudentB studentB) {
		this.studentB = studentB;
	}
	public StudentA() {
	}
	public StudentA(StudentB studentB) {
		this.studentB = studentB;
	}
}

public class StudentB {
	private StudentC studentC ;
	public void setStudentC(StudentC studentC) {
		this.studentC = studentC;
	}
	public StudentB() {
	}
	public StudentB(StudentC studentC) {
		this.studentC = studentC;
	}
}
public class StudentC {
	private StudentA studentA ;
	public void setStudentA(StudentA studentA) {
		this.studentA = studentA;
	}
	public StudentC() {
	}
	public StudentC(StudentA studentA) {
		this.studentA = studentA;
	}
}

也就是A依赖B,B依赖C,C依赖A。如果这时候创建实例A,将会抛出如下异常:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'a': Requested bean is currently in creation:
Is there an unresolvable circular reference?

Spring容器先创建单例StudentA,StudentA依赖StudentB,然后将A放在“当前创建Bean池”中,此时创建StudentB,StudentB依赖StudentC ,然后将B放在“当前创建Bean池”中,此时创建StudentC,StudentC又依赖StudentA, 但是,此时StudentA已经在池
中,所以会报错,,因为在池中的Bean都是未初始化完的,所以会依赖错误 ,(初始化完的Bean会从池中移除)。

下图来源于网络
在这里插入图片描述

② set方法注入单例

如果要说setter方式注入的话,我们最好先看一张Spring中Bean实例化的图
在这里插入图片描述
如图中前两步骤得知:Spring是先将Bean对象实例化之后再设置对象属性的

这时候我们再次获取StudentA对象将会成功获取到。

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new
		ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
		System.out.println(context.getBean("a", StudentA.class));
	}
}

那么为什么此时不会发生循环依赖异常呢?我们结合上面那张图看,Spring先是用构造实例化Bean对象 ,此时Spring会将这个实例化结束的对象放到一个Map中,并且Spring提供了获取这个未设置属性的实例化对象引用的方法。

结合我们的实例来看,当Spring实例化了StudentA、StudentB、StudentC后,紧接着会去设置对象的属性,此时StudentA依赖StudentB,就会去Map中取出存在里面的单例StudentB对象,以此类推,不会出现循环的问题。


我们常用的可能是如下方式:

@Component
public class StudentA {
    @Autowired
    StudentB studentB;
}

@Component
public class StudentB {
    @Autowired
    StudentC studentc;
}

@Component
public class StudentC {

    @Autowired
    StudentA studentA;
}

// 如下测试代码
@Api(tags = {"意见反馈"})
@Controller
@RequestMapping({"/advice","home/advice"})
public class SysAdviceController {

    @Autowired
    StudentA studentA;

    @ResponseBody
    @RequestMapping("/test")
    public ResponseBean test(){
        System.out.println("************************"+studentA);
        return ResultUtil.success();
    }
    //...
}    

这里我们可以看下获取的对象,其同样是完成了正常的实例化,并没有出现循环依赖异常。可以说这样属性注入本质与setXXX单例是一样的。
在这里插入图片描述


③ setter方式原型,prototype

scope="prototype" 意思是 每次请求都会创建一个实例对象。两者的区别是:有状态的bean都使用Prototype作用域,无状态的一般都使用singleton单例作用域。

这里直接说明测试结果:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'a': Requested bean is currently in creation:
Is there an unresolvable circular reference?

对于“prototype”作用域Bean,Spring容器无法完成依赖注入,因为“prototype”作用域的Bean,Spring容器不进行缓存,因此无法提前暴露一个创建中的Bean。
在这里插入图片描述

【2】从源码角度看Spring如何解决循环依赖

Spring的三级缓存

其实这里要了解Spring的三级缓存。下面是DefaultSingletonBeanRegistry中的一些常量:

  • 一级缓存 Map<String, Object> singletonObjects
  • 二级缓存 Map<String, Object> earlySingletonObjects
  • 三级缓存 Map<String, ObjectFactory<?>> singletonFactories
// 一级缓存,存放beanName和Bean instance
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

// 三级缓存  bean name - -objectFactory
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

// 二级缓存,存放beanName和Bean instance  early:早期的
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

// 注册序列的bean名称--单例哦
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

// 正在创建的bean的名称
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation =
		Collections.newSetFromMap(new ConcurrentHashMap<>(16));

[读书笔记]IOC容器的依赖注入详解我们看到了Bean创建的过程。
在这里插入图片描述
如上图所示,在doGetBean的方法中首先调用DefaultSingletonBeanRegistrygetSingleton(java.lang.String, boolean)方法尝试拿到单例缓存(也就是前面创建的,但是还可能没有完全完成bean的实例化)。

getSingleton方法是用来急切地检查手动注册的单例缓存。其允许当前创建的单例暴露出去,用来解决循环依赖。

// AbstractBeanFactory#doGetBean
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从一级缓存里面获取
	Object singletonObject = this.singletonObjects.get(beanName);
	// 如果一级缓存获取不到,且beanName是正在创建的Bean
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
	// 对一级缓存加锁
		synchronized (this.singletonObjects) {
			//从二级缓存里面获取
			singletonObject = this.earlySingletonObjects.get(beanName);
			
			// allowEarlyReference 这里传入的是true  允许bean提前暴露
			// 如果二级缓存里面没有,则从三级缓存获取工厂
			if (singletonObject == null && allowEarlyReference) {
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
				// 得到工厂生产的bean
					singletonObject = singletonFactory.getObject();
					// 放入二级缓存
					this.earlySingletonObjects.put(beanName, singletonObject);
					// 从三级缓存移除
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}

如果这里获取到了会直接调用bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);获取最终bean实例。然后判断是否需要格式化,之后返回。

如果这里获取不到,那么就会走创建流程。最终我们会在AbstractAutowireCapableBeanFactory的doCreateBean方法中看到这样的关键几步:

// 创建对象
instanceWrapper = createBeanInstance(beanName, mbd, args);

//单例  允许循环引用  是当前正在创建的bean,则调用addSingletonFactory  allowCircularReferences 默认为true
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));
}

// 依赖注入,实例化后期处理
Object exposedObject = bean;
try {
	// 属性赋值,解析依赖,循环依赖也发生在这个过程
	populateBean(beanName, mbd, instanceWrapper);
	// bean实例化的后置处理,比如beanpostprocessor   init-method等
	exposedObject = initializeBean(beanName, exposedObject, mbd);
}

我们看下这个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)) { //如果一级缓存不存在该bean
			this.singletonFactories.put(beanName, singletonFactory);//放入三级缓存
			this.earlySingletonObjects.remove(beanName);//从二级缓存移除
			this.registeredSingletons.add(beanName);//放入bean名称
		}
	}
}

这样当执行到populateBean时 ,如果两个对象相互依赖,那么当前对象(假设为A)的实例化就会触发另外一个对象(假设为B)的实例化。当B实例化时其又依赖了A就会从三级缓存(或二级缓存)获取A的引用完成实例化从而最终完成A的实例化。

那么二级缓存在这里面的作用呢?

假设AB相互依赖,AC相互依赖。那么B实例化后,就该进行C的实例化,这时C就可以从二级缓存来获取A的实例引用了,就不需要再从三级缓存获取工厂让其生产实例。

即假设只有AB相互依赖,其他对象不依赖AB时,这里二级缓存是没用的,一级和三级缓存起作用。

那么什么时候放入一级缓存呢?

仍旧在AbstractBeanFactory的doGetBean方法中。如下代码所示,首先运行createBean方法,其次会调用getSingleton方法。

// Create bean instance.
if (mbd.isSingleton()) {
	sharedInstance = getSingleton(beanName, () -> {
		try {
			return createBean(beanName, mbd, args);
		}
		catch (BeansException ex) {
			// Explicitly remove instance from singleton cache: It might have been put there
			// eagerly by the creation process, to allow for circular reference resolution.
			// Also remove any beans that received a temporary reference to the bean.
			destroySingleton(beanName);
			throw ex;
		}
	});
	bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

这里调用的getSingleton方法是getSingleton(String beanName, ObjectFactory<?> singletonFactory),如下所示如果未从一级缓存得到singletonObject ,那么其会调用addSingleton(beanName, singletonObject);方法。

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();
				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;
	}
}

addSingleton(beanName, singletonObject);方法如下所示:

protected void addSingleton(String beanName, Object singletonObject) {
	synchronized (this.singletonObjects) {
		// 放入一级缓存
		this.singletonObjects.put(beanName, singletonObject);
		// 从三级缓存移除
		this.singletonFactories.remove(beanName);
		// 从二级缓存移除
		this.earlySingletonObjects.remove(beanName);
		// 放入registeredSingletons中
		this.registeredSingletons.add(beanName);
	}
}

参考博文:
[读书笔记]IOC容器的依赖注入详解

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值