public ClassPathXmlApplicationContext( String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException { //调用父类构造方法进行相关初始化操作 super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } } 仔细看下面这行的具体代码:一层一层的调用父类的构造方法,
super(parent);
调到最后这一个父类
org.springframework.context.support.AbstractApplicationContext#AbstractApplicationContext(org.springframework.context.ApplicationContext)
public AbstractApplicationContext(@Nullable ApplicationContext parent) { this(); //父子容器初始化,parent可以为mvc的容器,这里为null setParent(parent); }
public AbstractApplicationContext() { this.resourcePatternResolver = getResourcePatternResolver(); }
最后调用这个资源模式处理器
protected ResourcePatternResolver getResourcePatternResolver() { //创建一个资源模式解析器,其实就是用来解析xml配置 return new PathMatchingResourcePatternResolver(this); } //解析环境变量的核心代码 org.springframework.context.support.AbstractRefreshableConfigApplicationContext#setConfigLocations
public void setConfigLocations(@Nullable String... locations) { if (locations != null) { Assert.noNullElements(locations, "Config locations must not be null"); this.configLocations = new String[locations.length]; //循环解析入参xml配置文件 for (int i = 0; i < locations.length; i++) { this.configLocations[i] = resolvePath(locations[i]).trim(); } } else { this.configLocations = null; } } org.springframework.context.support.AbstractRefreshableConfigApplicationContext#resolvePath protected String resolvePath(String path) { return getEnvironment().resolveRequiredPlaceholders(path); } public ConfigurableEnvironment getEnvironment() { if (this.environment == null) { this.environment = createEnvironment(); } return this.environment; } 注意这里new 了一个对象,先调用父类的构造方法 protected ConfigurableEnvironment createEnvironment() { return new StandardEnvironment(); }
public AbstractEnvironment() { customizePropertySources(this.propertySources); }
org.springframework.core.env.StandardEnvironment#customizePropertySources
就这样把系统属性和系统环境加入到propertySources中
protected void customizePropertySources(MutablePropertySources propertySources) { propertySources.addLast( new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties())); propertySources.addLast( new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment())); }
到此环境变量加入到spring容器中结束
总结:调用父类的构造方法,构造一个资源解析器,然后解析配置文件,通过构造方法调用到父类的customizePropertySources抽象方法,最后由子类来实现