prepareRefresh(); //准备工作 初始化spring状态 使spring处于运行状态
- 设置容器的启动时间
- 设置活跃状态为true
- 设置关闭状态为false
- 获取Environment对象,并加载当前系统的环境到Environment中
- 准备监听器和事件的集合对象,默认为空
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());
}
}
// Initialize any placeholder property sources in the context environment.
// 给子类进行扩展
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 创建环境对象,验证需要的属性文件是否都放到环境中
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
// 准备监听器集合,如果为空则创建,如果存在则清空再创建
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<>();
}
public interface ConfigurablePropertyResolver extends PropertyResolver {中的方法
- setRequiredProperties
- validateRequiredProperties对setRequiredProperties的属性进行验证
作用:对系统参数进行验证,比如-D ab=ba,需要ab这个属性,那么久可以进行扩展
扩展点:
public class MyApplicationContext extends ClassPathXmlApplicationContext {
public MyApplicationContext(String... configLocations) {
super(configLocations);
}
// 这里就要求了必须要有这个属性
@Override
protected void initPropertySources() {
getEnvironment().setRequiredProperties("OS");
}
}
validateRequiredProperties代码逻辑
代码逻辑是收集所有的异常信息,然后统一返回:MissingRequiredPropertiesException这个类的设计可以借鉴
@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;
}
}
监听器和事件集合再SpringBoot启动的时候是会存在applicationListeners的,spring是不需要的,提供来扩展,SpringBoot就进行了扩展。