在上一节中我们看来refresh()方法的作用,其中第一步就是创建并初始化beanFactory
在refresh()有行代码是做了创建并初始化beanFactory的工作
//创建beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//BeanFactory的预准备工作
prepareBeanFactory(beanFactory);
首先先obtainFreshBeanFactory()的作用
- DefaultListableBeanFactory类型的beanFactory
- 并将这个beanFactory赋值给了成员变量this.beanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//创建beanFactory
refreshBeanFactory();
//获取上面创建的beanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
/**AbstractRefreshableApplicationContext*/
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//通过createBeanFactory();创建了一个DefaultListableBeanFactory的beanFactory方法并赋值给了this.beanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
//直接返回了 this.beanFactory,也就是上一步refreshBeanFactory()创建的方法
return this.beanFactory;
}
}
至于prepareBeanFactory(beanFactory)方法,主要就是向beanFactory中添加了类加载器,一些解析器,还有一些BeanPostProcessor等等
spring IOC 源码阅读(三)之invokeBeanFactoryPostProcessors(beanFactory)