上一篇介绍了refresh
方法的概览,其中包含12个方法,接下来我们就依照顺序依次聊一下每个方法所实现的功能以及如何实现的。这篇文章先介绍【prepareRefresh
】与【ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
】。
<spring.version>4.3.9.RELEASE</spring.version>
1. prepareRefresh
方法
protected void prepareRefresh() {
// 记录容器启动的事件.
this.startupDate = System.currentTimeMillis();
// 设置对应的标志位
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// 扩展方法:
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 这里我没有用到,所以暂时也没有具体看是做什么的,后续再补充吧!
getEnvironment().validateRequiredProperties();
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
1.1 AbstractRefreshableWebApplicationContext#initPropertySources
protected void initPropertySources() {
ConfigurableEnvironment env = getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
}
}
在类AbstractApplicationContext
中该方法是空实现,而因为该工程是MVC工程,因此这里面使用的是调用其子类AbstractRefreshableApplicationContext
中的方法实现的。(待补充mvc相关知识。)
2. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
这个方法很重要,从字面上理解是获取BeanFactory。以包扫描的方式使用Spring时,走到该方法的类是:AbstractApplicationContext
,从下面的图中可以看出,AbstractApplicationContext
实现了BeanFacotory
接口。因此它不但包含BeanFacotory
接口的所有功能,还在其基础上增加了大量的扩展应用。
经过方法obtainFreshBeanFactory()
之后,ApplicationContext
就拥有了BeanFactory
的全部功能。
实际上该方法的主要功能是:会解析所有Spring的配置文件,这些配置文件我们一般都放在 resources目录下面。 将所有的配置文件中的bean都转换为BeanDefinition
。
我们有2种方式获取bean信息,方式一:通过配置文件的<bean>
。方式二:通过配置文件的扫描包的形式。<context:component-scan base-package="com.huanjie"></context:component-scan>
执行完该方法后,主要关注以下两个变量中的值
beanDefinitionName
- 存储
beanFactory
中的所有bean
的beanName
- 存储
beanDefinitionMap
- 存储
beanFactory
中的所有bean
的<beanName, beanDefinition>
- 存储
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// --- 【1】 ---