测试
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
完成对象实例化