本文主要解析AbstractApplicationContext类中refresh()方法中prepareRefresh()子方法的具体实现。废话不多说,直接上源码。
/**
* 1、设置容器启动时间
* 2、设置活跃状态为true
* 3、设置关闭状态为false
* 4、获取Environment对象,并加载当前系统的属性值到Environment对象中
* 5、准备监听器和时间的集合对象,默认为空的集合
*/
prepareRefresh();
(1)prepareRefresh()调用自身(AbstractApplicationContext类)的prepareRefresh()方法,具体实现如下:
protected void prepareRefresh() {
// Switch to active.
// 设置容器启动的时间
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();
// 1、检查是否存在环境变量如果存在直接用,不存在重更新获取
// 2、创建并获取环境对象、验证需要的属性文件是否符合
getEnvironment().validateRequiredProperties();
// 判断刷新前的应用程序监听器集合是否为空,如果为空,则将监听器添加到此集合中
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 创建刷新前的监听事件集合
this.earlyApplicationEvents = new LinkedHashSet<>();
}
(2)在(1)中initPropertySources()方法,默认无实现,主要用于业务拓展,比如:可以在Spring启动时内置一些环境变量。
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
(3)在(1)中getEnvironment()方法,实现如下。
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();//创建ConfigurableEnvironment 新环境
}
return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
(4)在(1)中validateRequiredProperties()方法,调用AbstractEnvironment类中validateRequiredProperties()的方法。
@Override
public void validateRequiredProperties() throws MissingRequiredPropertiesException {
this.propertyResolver.validateRequiredProperties();
}
最终,调用到AbstractPropertyResolver类的validateRequiredProperties()方法
//验证setRequiredProperties指定的每个属性是否存在并解析为非null值
@Override
public void validateRequiredProperties() {
MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
for (String key : this.requiredProperties) {
if (this.getProperty(key) == null) {
ex.addMissingRequiredProperty(key);
}
}
if (!ex.getMissingRequiredProperties().isEmpty()) {
throw ex;
}
}
(5)最后判断前置监听是否为null,若为null则新增,部位null则清空之前的监听,添加现在的监听。并初始化前置事件集合。
// 判断刷新前的应用程序监听器集合是否为空,如果为空,则将监听器添加到此集合中
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 创建刷新前的监听事件集合
this.earlyApplicationEvents = new LinkedHashSet<>();