TIPS:本文主要是讲述在spring框架中的beanFactory初始化过程,在spring-boot稍有不同。
BeanFactory和ApplicationContext
在spring IOC容器的设计中有两个主要的容器系列:
- BeanFactory:实现BeanFactory接口的简单容器系列,这个系列的容器只实现了容器的最基本功能。
- ApplicationContext:它是容器的高级形态,继承了BeanFactory接口,应用上下文在简单容器的基础上,增加了许多面向框架的特性,同时对应用环境做了许多适配。常见的实现有:
- ClassPathXmlApplicationContext
- FileSystemXmlApplicationContext
- GenericXmlApplicationContext
IoC容器的设计
从上图可以看到ApplicationContext实现了BeanFactory接口容器该有的功能,它也一样不少
IoC容器的初始化过程
IoC容器的初始化过程分为3歩
资源定位
beanDefination载入
bean注册
以FileSystemXmlApplicationContext为例进行讲解:
FileSystemXmlApplicationContext applicationContext =
new FileSystemXmlApplicationContext("classpath:/bean.xml");
通常手动创建ApplicationContext的步骤如上述所示。
beanDefinition的定位
/*构造器*/
public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{configLocation}, true, (ApplicationContext)null);
}
/*在构造器中调用以下方法*/
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh,
@Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
Ioc的触发点
在初始化FileSystemXmlApplicationContext的过程中
this.setConfigLocations(configLocations)
中的configLocations是资源(BeanDefinition
)所在的文件路径,而beandefinition
的定位最初是在refresh()
方法中触发的
refresh()
方法是AbstractApplicationContext
中的方法:该方法进行IoC容器的触发点
beanDefinition的载入
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
obtainFreshBeanFactory()
方法主要功能是获取一个ConfigurableListableBeanFactory
/* AbstractApplicationContext#refreshBeanFactory(),
AbstractApplicationContext#getBeanFactory()都是抽象方法,具体实现在
AbstractRefreshableApplicationContext中实现
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
/*AbstractRefreshableApplicationContext # refreshBeanFactory()*/
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
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);
}
}
在AbstractRefreshableApplicationContext
的refreshBeanFactory()
方法主要干了3件事:
- 创建了一个
DefaultListableBeanFactory
- 调用
customizeBeanFactory(beanFactory)
方法进行定制化扩展 - 调用
loadBeanDefinitions(beanFactory)
进行beanDefinition
的载入,具体是由XmlBeanDefinitionReader
进行载入的,资源定位
也是在此时进行的。
**TIPS**
:refreshBeanFactory()方法只是将xml
中定义的bean
进行了注册,对于由注解@Component
标记的bean是在获取BeanFactory后调用invokeBeanFactoryPostProcessors(beanFactory)
方法注册完成的。
(载入的过程其实就是一个将用户定义的bean
转换成IoC容器内部数据结构
的过程,而这个数据结构就是BeanDefinition
,每一个bean
都被转换成BeanDefinition
)
BeanDefinition在IoC容器中的注册
在BeanDefinition在IoC容器中载入和解析过后,需要将这些BeanDefinition向IoC容器注册,在DefaultListableBeanFactory中,是通过一个HashMap来持有载入的BeanDefinition的。
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap(256);
将解析得到的BeanDefinition
向IoC容器中的beanDefinitionMap
注册的过程是在载入beanDefinition完成后进行的。
具体过程是:
XmlBeanDefinitionReader.loadBeanDefinitions(configLocations) ->
XmlBeanDefinitionReader.registerBeanDefinitions(Document doc, Resource resource) ->
DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(
Document doc, XmlReaderContext readerContext) ->
DefaultBeanDefinitionDocumentReader.parseBeanDefinitions() ->
DefaultBeanDefinitionDocumentReader.parseDefaultElement() ->
DefaultBeanDefinitionDocumentReader.processBeanDefinition() ->
BeanDefinitionReaderUtils.registerBeanDefinition() ->
DefaultListableBeanFactory.registerBeanDefinition(){
...
this.beanDefinitionMap.put(beanName, beanDefinition);
}
以上的内容只是IoC容器初始化的过程,不涉及IoC容器的依赖注入。