ConfigFileApplicationListener通过在容器启动的过程中监听相应的事件来加载配置。
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
onApplicationEnvironmentPreparedEvent(
(ApplicationEnvironmentPreparedEvent) event);
}
if (event instanceof ApplicationPreparedEvent) {
onApplicationPreparedEvent(event);
}
}
private void onApplicationEnvironmentPreparedEvent(
ApplicationEnvironmentPreparedEvent event) {
//从spring.factories中获取所有的EnvironmentPostProcessor
List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
//当前对象也是一个EnvironmentPostProcessor
postProcessors.add(this);
//排序
AnnotationAwareOrderComparator.sort(postProcessors);
for (EnvironmentPostProcessor postProcessor : postProcessors) {
//加载配置
postProcessor.postProcessEnvironment(event.getEnvironment(),
event.getSpringApplication());
}
}
/**
* 当前EnvironmentPostProcessor的处理逻辑
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
addPropertySources(environment, application.getResourceLoader());
}
protected void addPropertySources(ConfigurableEnvironment environment,
ResourceLoader resourceLoader) {
RandomValuePropertySource.addToEnvironment(environment);
//new一个loader(在spring.factories文件中找到所有的PropertySourceLoader,如properties,yml文件的Loader[PropertiesPropertySourceLoader,YamlPropertySourceLoader])并load
new Loader(environment, resourceLoader).load();
}
}