接着来分析 ClassPathXmlApplicationContext 的构造函数,前一篇文章中,我们分析了 supper(parent),现在我们来分析 setConfigLocations。
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
private Resource[] configResources;//资源数组
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
// 调用父类构造函数,进行相关对象的创建,包括 Environment 对象的创建
super(parent);
// 设置配置资源路径
setConfigLocations(configLocations);
// 刷新标志位通过构造参数传递进来,为 true
if (refresh) {
/ /执行刷新,整个IOC 容器启动的核心
refresh();
}
}
}
我们的重点在与分析 Spring 设置加载资源路径,那么来看 setConfigLocations 的代码。
public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
implements BeanNameAware, InitializingBean {
// 保存配置文件路径的数组
@Nullable
private String[] configLocations;
public void setConfigLocations(@Nullable 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 {
// 赋值 null,等待垃圾回收
this.configLocations = null;
}
}
}
方法的入参可以传入一个字符串数组的,那么表示它可以一次性接受多个配置文件,使用配置文件的目的是让 Spring 知道,那些 Bean 的生命周期是需要由 Spring 来管理的,将所有的 Bean 配置在一个配置文件中实在是太臃肿了,因此可以按模块配置 Bean,将其划分在不同的配置文件中。
在 setConfigLocations 方法中有调用了一个 resolvePath 方法,resolvePath 直译过来就是解析路径,有人可能会想,路径有什么好解析的。先来来看一下 resolvePath 的代码。
public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
implements BeanNameAware, InitializingBean {
protected String resolvePath(String path) {
// 获取环境对象并解析占位符
return getEnvironment().resolveRequiredPlaceholders(path);
}
}
只有简单的 一行代码,获取环境对象并解析占位符。怎么理解呢?对于 ${xxx} 大家都不会陌生吧,在 Spring 的配置文件中经常会配置数据源。
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username=root
password=root
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
${}就是我们常说的占位符,括号内的部分会在 Spring 容器启动的过程中被替换为真正的值。那么 setConfigLocations 方法中的解析路径又是怎么回事呢?其实跟替换数据源中的占位符一个道理。不过这里替换占位符中的变量用的是我们系统环境变量,比如你的电脑的用户名 username 为olderSix,你在启动 Spring 容器的时候使用的事ClassPathXmlApplicationContext("classpath:spring-beans-${username}.xml"),那么经过解析路径之后,设置的资源路径文件名将会变为 spring-beans_olderSix.xml,后面解析配置文件的时候将会去找 spring-beans_olderSix.xml,如果找不到该文件将会抛出异常。这个功能在 Spring 中并不常用,细节大家有兴趣可以自己 debug 去看看。
增加一个 spring-beans-olderSix.xml 的配置文件,注意需要与自己的主机名保持一致。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="helloWorld" class="com.demo.beans.HelloWorld"></bean>
</beans>
来看启动类:
public class XmlStartApplication {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beans-$username}.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.say();
}
}
可以看到,虽然使用的配置路径是 classpath:spring-beans-${username}.xml,但是任然可以从容器中获取到 HelloWorld 的实例对象,说明 Spring 帮我们进行了路径解析。
接着来说说 getEnvironment(),直接来看代码。
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
// 获取 StandardEnvironment 实例
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
// 创建一个 ConfigurableEnvironment 实例
this.environment = createEnvironment();
}
return this.environment;
}
// 创建一个新的 ConfigurableEnvironment
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
}
可以看到直接是 new 了一个StandardEnvironment对象。看一下 StandardEnvironment 的定义。
public class StandardEnvironment extends AbstractEnvironment {
// 系统环境属性源名称
public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment";
// JVM 系统属性属性源名称
public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties";
public StandardEnvironment() {
}
// 创建一个新的 StandardEnvironment, 其中包含特殊的可变的属性资源
protected StandardEnvironment(MutablePropertySources propertySources) {
super(propertySources);
}
// 自定义属性资源
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
// 向属性资源集合中添加 JVM 环境属性
propertySources.addLast(
new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
// 向属性资源集合中添加系统环境属性
propertySources.addLast(
new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}
}
这里有两个属性,一个表示系统环境属性,一个表示 JVM 系统属性。