Spring 中循环依赖问题

在这里插入图片描述

测试

public class TestBean implements InitializingBean, BeanNameAware {


	private ItBean itBean;

	/**
	 * 构造函数
	 */
	public TestBean(){
		System.err.println("TestBean 构造器...");
	}


	public ItBean getItBean() {
		return itBean;
	}

	public void setItBean(ItBean itBean) {
		this.itBean = itBean;
	}

	/**
	 * InitializingBean 接口实现
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		System.err.println("TestBean afterPropertiesSet...");
	}


	public void print() {
		System.err.println("print方法业务逻辑执行");
	}

	@Override
	public void setBeanName(String name) {
		System.err.println("TestBean BeanNameAware...");
	}
}
public class ItBean {

	private TestBean testBean;

	public TestBean getTestBean() {
		return testBean;
	}

	public void setTestBean(TestBean testBean) {
		this.testBean = testBean;
	}

	/**
	 * 构造函数
	 */
	public ItBean(){
		System.out.println("ItBean 构造器...");
	}
}


xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="testBean" class="com.liu.cyclic.bean.TestBean">
		<property name="itBean" ref="itBean"/>
	</bean>

	<bean id="itBean" class="com.liu.cyclic.bean.ItBean">
		<property name="testBean" ref="testBean"/>
	</bean>
</beans>

TestBean依赖ItBean,而ItBean又依赖TestBean

原理图

在这里插入图片描述

源码

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
首先调用TestBean的无参构造方法,创建一个对象,只的创建对象并没有设置属性之类的.
在这里插入图片描述


protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			//创建Bean 调用无参数构造方法,没有属性赋值
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
	...
放入三级缓存中

在这里插入图片描述

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
...

	/**
		 * 缓存中判断是否需要提前暴露,
		 */
		// 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");
			}
			//加入3级缓存
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

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

向下执行设置属性
Object exposedObject = bean;
		try {
			/**
			 * 设置属性
			 */
			populateBean(beanName, mbd, instanceWrapper);
			/**
			 * 调用初始化方法 Aware接口的方法init-method等 BeanPostProcessor方法
			 */
			exposedObject = initializeBean(beanName, exposedObject, mbd);
populateBean方法
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...
		if (pvs != null) {
		//设置属性
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}
applyPropertyValues方法

在这里插入图片描述


protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
	...
else {
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();
				//判断是否必要的,这里进入第二个Bean的实例化流程
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;


org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveValueIfNecessary

在这里插入图片描述
在这里插入图片描述


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.
		if (value instanceof RuntimeBeanReference) {
			RuntimeBeanReference ref = (RuntimeBeanReference) value;
			return resolveReference(argName, ref);
		}
org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveReference

@Nullable
	private Object resolveReference(Object argName, RuntimeBeanReference ref) {
		try {
			Object bean;
			String refName = ref.getBeanName();
			refName = String.valueOf(doEvaluate(refName));
			if (ref.isToParent()) {
				if (this.beanFactory.getParentBeanFactory() == null) {
					throw new BeanCreationException(
							this.beanDefinition.getResourceDescription(), this.beanName,
							"Can't resolve reference to bean '" + refName +
									"' in parent factory: no parent factory available");
				}
				bean = this.beanFactory.getParentBeanFactory().getBean(refName);
			}
			else {
				//从工厂中获取Bean再从进入doGetBean
				bean = this.beanFactory.getBean(refName);
				this.beanFactory.registerDependentBean(refName, this.beanName);
			}
			if (bean instanceof NullBean) {
				bean = null;
			}
			return bean;
		}

再次进入org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean方法
这里创建的是第二个对象
在这里插入图片描述
再向下调用createBean方法
在这里插入图片描述

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean方法

在这里插入图片描述

创建了ItBean使用无参构造,下面再次放入三级缓存中,再进入设置属性
在这里插入图片描述

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues方法中

else {
				String propertyName = pv.getName();// testBean
				Object originalValue = pv.getValue();
				//
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;

org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveReference

在这里插入图片描述

再次

在这里插入图片描述

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

在这里插入图片描述
返回到 org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveReference
在这里插入图片描述
再注册第二个Bean

再返回org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveValueIfNecessary

一直回到 org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

在这里插入图片描述
完成第二个Bean的实例化,

回到第一个Bean的流程中

org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveReference
在这里插入图片描述

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean


		/**
		 * 获取单例对象 尝试去缓存中获取
		 */
		// Eagerly check singleton cache for manually registered singletons.
		Object sharedInstance = getSingleton(beanName);
返回 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

在这里插入图片描述
完成对象实例化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值