欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring源码分析(1)- Environment环境获取与路径解析

程序员文章站 2022-04-22 10:36:49
...

主函数

public class App {
    public static void main(String[] args) {
        ApplicationContext ac = new
                ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) ac.getBean("student");
        System.out.println(student);
    }
}

执行构造方法

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
			throws BeansException {
	super(parent);
	setConfigLocations(configLocations);
	if (refresh) {
		refresh();
	}
}

其中setConfigLocations(configLocations);代码块执行配置文件地址的解析,以及环境的初始化,代码块如下所示:

public void setConfigLocations(String... locations) {
	if (locations != null) {
		Assert.noNullElements(locations, "Config locations must not be null");
		this.configLocations = new String[locations.length];
		for (int i = 0; i < locations.length; i++) {
			this.configLocations[i] = resolvePath(locations[i]).trim();
		}
	}
	else {
		this.configLocations = null;
	}
}

其中this.configLocations[i] = resolvePath(locations[i]).trim();代码块进行配置文件地址解析,实现如下:

protected String resolvePath(String path) {
	return getEnvironment().resolveRequiredPlaceholders(path);
}

其中getEnvironment()用于获取相关环境,包括JVM配置的相关环境和计算机系统所配置的环境变量。具体实现会new一个StandardEnvironment对象,StandardEnvironment对象的具体实现如下所示。在生成StandardEnvironment对象时会首先调用其父类AbstractEnvironment的构造方法,在AbstractEnvironment的构造方法中会调用customizePropertySources方法来获取相关的环境变量。

public class StandardEnvironment extends AbstractEnvironment {
    public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment";
    public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties";

    public StandardEnvironment() {
    }

    protected void customizePropertySources(MutablePropertySources propertySources) {
        propertySources.addLast(new MapPropertySource("systemProperties", this.getSystemProperties()));
        propertySources.addLast(new SystemEnvironmentPropertySource("systemEnvironment", this.getSystemEnvironment()));
    }
}

如上所示,其中this.getSystemProperties()的实现主要是调用System.getProperties()方法来获取JVM环境变量。
this.getSystemEnvironment()的实现主要是调用System.getenv()来获取本机所配置的环境变量。
在获取了StandardEnvironment对象后,就是进行配置文件路径的解析了,调用resolveRequiredPlaceholders(path) 将路径中含有${XXX}的字符串做相应的替换,然后进行返回。

相关标签: Spring java