BeanFactory getBean 流程:getBean -> doGetBean -> getSingleton -> singletonFactory.getObject() -> createBean ->doCreateBean->initializeBean
1. getSingleton
从缓存中获取已经创建的单例bean,或者是返回一个 early reference,从而新创建一个bean
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);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
2. doGetBean
不同的scope生成bean的策略不同
protected T doGetBean(){
// 查看是否缓存在 singletonObjects 中
Object sharedInstance = getSingleton(beanName);
//如果不为空,则直接返回缓存中
if (sharedInstance != null && args == null) {
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}else {
//如果未能在缓存中找到bean,需要根据bean的scope新建一个bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory
3. createBean
给BeanPostProcessor一个创建并返回代理bean的机会
protected Object createBean(){
// 生成BeanPostProcessor的代理类
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
...
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
4. doCreateBean
真正的实例化从这里开始
protected Object doCreateBean(){
BeanWrapper instanceWrapper = null;
//创建BeanWrapper实例:实例化bean
instanceWrapper = createBeanInstance(beanName, mbd, args);
// 初始化bean
Object exposedObject = bean;
//为bean添加属性
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
...
return exposedObject;
}
5. initializeBean
该方法完成了bean的实例化:调用bean的初始化方法:afterPropertiesSet方法;调用PostBeanProcessor的方法生成了增强的bean。
protected Object initializeBean(){
//触发aware 接口的set方法
invokeAwareMethods(beanName, bean);
// PostBeanProcessor方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
//调用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}