Spring
源码 - 容器刷新#prepareRefresh()
Spring
版本:5.3.13-release
# 1、prepareRefresh()
准备刷新上下文环境
prepareRefresh()
为Spring
容器刷新的第一个方法,其意义就是准备刷新上下文环境。初始化容器中的一些状态为后续的容器刷新工作做准备。
AbstractApplicationContext#prepareRefresh()
代码:
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
// Switch to active.
// 1.设置容器的启动时间
this.startupDate = System.currentTimeMillis();
// 2.设置容器关闭状态为 false
this.closed.set(false);
// 3.设置容器活跃状态为 true
this.active.set(true);
// 记录日志
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 留给子类覆盖, 初始化属性资源
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 创建并获取 Environment 对象, 验证系统需要的属性文件是否都已加载入 Environment 中
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
// 5.准备监听器和事件的集合对象, 默认为空集合
// 判断刷新前的应用程序监听器集合是否为空, 如果为空则将监听器集合添加到此集合中
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
// 如果不为空, 则清空监听器集合元素
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 创建刷新前的事件监听集合
this.earlyApplicationEvents = new LinkedHashSet<>();
}
initPropertySources()
:Spring
并没有实现该方法。留给子类覆盖, 初始化属性资源。getEnvironment().validateRequiredProperties()
:创建并获取Environment
对象, 验证系统需要的属性文件是否都已加载入Environment
中,对系统属性进行校验。
GitHub源码地址:https://github.com/kapbc/kapcb-spring-source/tree/master/Spring-Framework-v5.3.13
备注:此文为笔者学习
Spring
源码的笔记,鉴于本人技术有限,文中难免出现一些错误,感谢大家批评指正。