上一篇留了一个TODO,这里从DefaultListableBeanFactory#preInstantiateSingletons开始继续跟踪源码。

loadBeanDefinitions结束之后,DefaultListableBeanFactory#beanDefinitionNames中保存了beanName。这里通过预调用AbstractBeanFactory#getBean(String)实例化所有的bean。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

继续跟踪源码来到AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])中的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}

上一篇提到注册BeanPostProcessor,这里的resolveBeforeInstantiation即检查注册的BeanPostProcessor是否实现了InstantiationAwareBeanPostProcessor接口,如果是,这里会调用实现的postProcessBeforeInstantiation方法。

接着AbstractAutowireCapableBeanFactory#createBeanInstance实例化bean并包装为BeanWrapper;AbstractAutowireCapableBeanFactory#populateBean会检查注册的BeanPostProcessor是否实现了InstantiationAwareBeanPostProcessor接口,如果是,这里会调用实现的postProcessAfterInstantiation、postProcessPropertyValues方法。AbstractAutowireCapableBeanFactory#applyPropertyValues会尝试使用BeanWrapper注册的PropertyEditor修改property。

后面的过程和BeanFactory javadoc中的描述一致,会依次调用

  1. postProcessBeforeInitialization methods of BeanPostProcessors
  2. InitializingBean’s afterPropertiesSet
  3. a custom init-method definition
  4. postProcessAfterInitialization methods of BeanPostProcessors

createBean占了大半篇幅,这里重新回到开头,createBean方法调用结束后得到sharedInstance,接着检查sharedInstance是否为FactoryBean实例,如果是,会调用FactoryBean#getObject方法,方法的返回值作为最后的返回结果。