如果是xml 作为配置文件启动Spring:
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
首先解析super(parent) 方法,这个方法是进入AbstractApplicationContext的构造,调用以下方法:
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
this() 方法解析:
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
getResourcePatternResolver方法解析:
protected ResourcePatternResolver getResourcePatternResolver() {
// 是一个Ant模式通配符的Resource查找器,可以通过ant 表达式获取资源路径,Resource对象等
// 可以参考:https://www.cnblogs.com/dw3306/p/15690354.html
return new PathMatchingResourcePatternResolver(this);
}
PathMatchingResourcePatternResolver类,是一个用于获取指定文件的类,例如获取xml配置文件,或者yml 配置文件等,例如:
- 获取文件系统文件
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resource = resolver.getResource("file:pom.xml");
Assert.assertNotNull(resource);
Assert.assertNotNull(resource.getInputStream());
- 从类路径下获取指定的文件
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//从classpath下获取单个的资源文件,classpath下没有将尝试把资源当做一个UrlResource
Resource resource = resolver.getResource("applicationContext.xml");
Assert.assertNotNull(resource);
Assert.assertNotNull(resource.getInputStream());
之后是setParent方法的执行,主要是获取环境变量并且和现有的属性集合进行合并,具体内容如下:
@Override
public void setParent(@Nullable ApplicationContext parent) {
// 获取环境变量
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
merge 方法内容如下,主要是从Profile文件中获取和当前环境中获取并添加到propertySources集合中:
@Override
public void merge(ConfigurableEnvironment parent) {
for (PropertySource<?> ps : parent.getPropertySources()) {
if (!this.propertySources.contains(ps.getName())) {
this.propertySources.addLast(ps);
}
}
String[] parentActiveProfiles = parent.getActiveProfiles();
if (!ObjectUtils.isEmpty(parentActiveProfiles)) {
synchronized (this.activeProfiles) {
Collections.addAll(this.activeProfiles, parentActiveProfiles);
}
}
String[] parentDefaultProfiles = parent.getDefaultProfiles();
if (!ObjectUtils.isEmpty(parentDefaultProfiles)) {
synchronized (this.defaultProfiles) {
this.defaultProfiles.remove(RESERVED_DEFAULT_PROFILE_NAME);
Collections.addAll(this.defaultProfiles, parentDefaultProfiles);
}
}
}
其中主要需要注意的是PropertySource对象,通过点击getPropertySources方法的实现我找到一个类:MutablePropertySources 这个类中存在一个List集合,经过查询资料知道,PropertySource是一个主要用于保存配置文件,环境变量,命令行参数等信息的类,而这个List列表则保存了Spring框架所有的配置文件,环境变量,命令行参数内容
private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
也就是说这这段代码是Spring框架的前置准备部分:
- 创建文件解析对象PathMatchingResourcePatternResolver
- 获取环境变量
9660

被折叠的 条评论
为什么被折叠?



