之前分析了准备创建bean的一些操作.
现在来分析doCreateBean()这个方法做了哪些事.
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
BeanWrapper instanceWrapper = null;
// 判断是不是singleton类型的
if (mbd.isSingleton()) {
// 如果是,则从缓存中移除
instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//1、实例化bean
instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}
// 获取实例
Object bean = instanceWrapper.getWrappedInstance();
// 获取实例的类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized(mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// bean合并后的处理,Autowired注解就是通过这个方法实现例如类型的预解析
this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
} catch (Throwable var17) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
}
mbd.postProcessed = true;
}
}
// 判断是否提前暴露ObjectFactory,包括三个条件:
// 1、isSingleton:是否是单例模式
// 2、allowCircularReferences:是否允许循环依赖,可以设置
// 3、isSingletonCurrentlyInCreation:当前bean是否是正在创建的状态
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
}
// 2、如果允许提前暴露,则以beanName为key,ObjectFactory为value放到三级缓存中
this.addSingletonFactory(beanName, () -> {
return this.getEarlyBeanReference(beanName, mbd, bean);
});
}
// 记录暴露的对象
Object exposedObject = bean;
try {
// 3、填充属性,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始化依赖bean
this.populateBean(beanName, mbd, instanceWrapper);
// 4、调用初始化,比如init-method
exposedObject = this.initializeBean(beanName, exposedObject, mbd);
} catch (Throwable var18) {
if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
throw (BeanCreationException)var18;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
}
// 如果允许提前暴露
if (earlySingletonExposure) {
// 5、调用方法,获取提前暴露出去的对象,注意这里的第二个参数是false
// 只有在发生循环依赖的时候才会不为空
Object earlySingletonReference = this.getSingleton(beanName, false);
if (earlySingletonReference != null) {
// 如果相等,说明在初始化的时候,bean没有被改变,即没有被增强
if (exposedObject == bean) {
// 暴露的bean的值改编成缓存中获取的earlySingletonReference
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
// 获取所有依赖的bean
String[] dependentBeans = this.getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
String[] var12 = dependentBeans;
int var13 = dependentBeans.length;
for(int var14 = 0; var14 < var13; ++var14) {
String dependentBean = var12[var14];
// 检测依赖的bean是否已经创建
if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
// 如果有依赖的bean没有被创建,说明出现了循环依赖,那么会抛异常
// 因为bean创建后其所依赖的bean一定已经创建了.
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 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
try {
// 注册DisposableBean,配置了destroy-method,这里需要注册以便在销毁时候调用
this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
// 返回创建好的对象
return exposedObject;
} catch (BeanDefinitionValidationException var16) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
}
}
总结一下,上面的代码逻辑:
1、如果是单例,则需要清除缓存.
2、实例化bean,将BeanDefinition转为BeanWrapper.转换的过程比较复杂,可以大致概括为:
- 如果存在工厂方法则使用工厂方法进行实例化
- 一个类有多个构造函数,每个构造函数都有不同的参数,所以需要根据参数锁定构造函数并进行实例化
- 如果既不存在工厂方法也不存在带有参数的构造函数,则使用默认的构造函数进行bean的实例化
3、MergedBeanDefinitionPostProcessor的应用.
4、依赖处理
是否提前暴露一个ObjectFactory,需要满足三个条件:
- isSingleton
- allowCircularReferences
- isSingletonCurrentlyInCreation
5、属性填充.将所有属性填充到bean的实例中
6、循环依赖检查
7、注册DisposableBean,配置了destroy-method,这里需要注册以便在销毁时候调用
8、完成创建并返回