前面介绍了Spring的一些基础知识和简单的用法,本篇开始分析Spring的IoC容器。BeanFactory是IoC容器的基础,所以接下来的分析都是基于BeanFactory的。
IoC启动过程:
启动
加载资源文件
解析资源文件
注册BeanDefinition
结束
IoC容器的启动可分为三步,加载资源文件、解析资源文件、注册BeanDefinition。本篇分析资源文件加载过程。
Spring中资源文件加载主要有两个接口,Resource和ResourceLoader,前者提供了对资源文件的定位、是否存在、是否可读、是否打开、是否文件、获取URL,获取File、获取FileName等一系列功能。后者提供了Resource对象获取,自定义资源文件协议解析等功能。加载资源文件的过程会涉及到类加载机制,且不是我们分析IoC容器的重点,所以本篇不会做太多深入的分析。测试类
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import java.io.IOException;
public class MyTest {
@Test
public void test1() {
// 从资源文件夹下加载
Resource resource = new ClassPathResource("v2/day01.xml");
print(resource);
}
@Test
public void test2() {
// 使用类信息加载
Resource resource = new ClassPathResource("day01.xml", MyTest.class);
print(resource);
}
@Test
public void test3() {
// 使用类加载器从资源文件夹下加载
Resource resource = new ClassPathResource("v2/day01.xml", MyTest.class.getClassLoader());
print(resource);
}
@Test
public void test4() {
// 使用DefaultResourceLoader加载
Resource resource = new DefaultResourceLoader().getResource("v2/day01.xml");
print(resource);
}
// 打印资源文件内容
public void print(Resource resource) {
byte[] read = new byte[10000];
try {
resource.getInputStream().read(read, 0, read.length);
System.out.println(new String(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行测试类,将会打印day01.xml的内容。注意资源文件的路径
先分析ClassPathResource的加载过程,再DefaultResourceLoader的加载过程
1. ClassPathResource对象创建过程
创建ClassPathResource对象
public ClassPathResource(String path, @Nu