在上篇博客介绍了Ioc容器创建的大概过程,但BeanFactory创建的具体细节没有说明,好!接下来就让我们来看下BeanFactory创建的具体细节
首先我们来回顾一下前面内容中介绍过的类AbstractApplicationContext
中的方法refresh
内部出现的一行代码
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
接下来进入到方法obtainFreshBeanFactory
中去看看具体实现(该方法的实现也是在类AbstractApplicationContext
中)
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if(this.logger.isDebugEnabled()) {
this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
对于上面的代码,Emphasis是在方法refreshBeanFactory
上,那好!接下来来方法refreshBeanFactory
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
类AbstractApplicationContext
中的方法refreshBeanFactory()
是个抽象方法,所以需要到继承了AbstractApplicationContext类的子类中才有该方法的具体实现
从上图得知有两个类·AbstractRefreshableApplicationContext
和GenericApplicationContext
实现了抽象方法refreshBeanFactory()
接下来我们就进入到类·AbstractRefreshableApplicationContext,看看方法的具体实现,代码如下:
protected final void refreshBeanFactory() throws BeansException {
//如果存在BeanFactory对象,销毁该对象,并重新创建BeanFactory
if(this.hasBeanFactory()) {
this.destroyBeans();
this.closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = this.createBeanFactory();
beanFactory.setSerializationId(this.getId());
this.customizeBeanFactory(beanFactory);
//解析和登记Bean对象
this.loadBeanDefinitions(beanFactory);
Object var2 = this.beanFactoryMonitor;
synchronized(this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
} catch (IOException var5) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
}
}
看上面的代码中,我们看到创建了一个DefaultListableBeanFactory对象beanFactory, 具体过程见下面的代码
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(this.getInternalParentBeanFactory());
}
两位有一个方法loadBeanDefinitions(beanFactory)
也需要作为重点分析下,在类AbstractRefreshableApplicationContext中该方法是个*抽象方法:
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory var1) throws BeansException, IOException;
下面的代码是类AbstractXmlApplicationContext中的该方法loadBeanDefinitions(beanFactory)
的实现代码
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
this.initBeanDefinitionReader(beanDefinitionReader);
this.loadBeanDefinitions(beanDefinitionReader);
}
在上面的代码中看到下面所示两个重要操作:
- new XmlBeanDefinitionReader(beanFactory)
- loadBeanDefinitions(beanDefinitionReader)
综上所述:BeanFactory创建的详细过程看下面的序列图: