Spring源码:Spring加载指定的配置文件

Spring加载指定的配置文件

Spring可以通过加载xml配置文件向容器中添加bean对象,这种方式需要在创建spring容器时指定xml配置文件的路径,spring按照路径将xml中的bean定义信息加载为BeanDefinition对象。

创建spring容器,并设置要加载的配置文件

在main方法中使用构造方法直接创建容器,参数可以以classpath、classpath*开头。可以使用占位符。

public static void main(String[] args) {
	//使用ClassPathXmlApplicationContext创建Spring容器,参数为要加载的配置文件路径
	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath*:/*.xml");
}

classpath与classpath*的区别

classpath:只会读取当前项目中 target/classes 文件夹下的资源。classpath指项目的 target/classes路径。
classpath*:读取当前项目以及依赖jar中target/classes文件夹下的资源。
注意:classpath需要遍历所有的classpath,加载速度是很慢的。尽量避免使用classpath

调用构造方法,将入参赋值给成员属性

1、main方法中的构造方法,会将配置文件路径放到数组中,并且指定刷新标志为true,设置父容器为null。构造方法源码如下:

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
	this(new String[] {configLocation}, true, null);
}

2、会调用三个参数的构造方法,设置父容器,设置配置文件路径,并创建spring容器。构造方法源码如下:

// 核心构造函数,设置此应用上下文的配置文件的位置,并判断是否自动刷新上下文
public ClassPathXmlApplicationContext(
		String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
		throws BeansException {

	// 将用父类的构造方法,设置父容器
	super(parent);
	//设置应用上下文的配置文件的位置,将配置文件的路径存放到configLocations字符串数组中
	setConfigLocations(configLocations);
	// 如果刷新表示为true,则会调用refresh()方法加载spring容器
	if (refresh) {
		refresh();
	}
}

3、构造方法中通过调用AbstractRefreshableConfigApplicationContext类中的setConfigLocations(@Nullable String… locations)方法将配置文件路径设置给AbstractRefreshableConfigApplicationContext类中的成员变量。在该方法中会解析配置文件路径中的占位符。占位符如何解析会在之后的文章中讲解。
给容器设置配置文件路径的方法源码如下:

// 将配置文件的路径放到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 {
		this.configLocations = null;
	}
}

4、将配置文件的路径设置给spring容器的成员变量,后续spring会读取配置文件,将配置文件中的bean定义信息解析为BeanDefinition对象,然后通过BeanDefinition对象在加载bean对象到spring容器中。在之后文章中会有spring源码解析。

码字不易,大家点个关注点个赞。大家一起卷。

你可能感兴趣的:(Spring,spring,java,后端)