Spring中的资源Resource 以及分类(多种资源的实现类)
Spring中的资源都被封装成 Resource 对象
以上是我测试代码的项目编译后的目录结构,target 所在的目录是
D:\\IdeaProjects\\study-spring\\
public void printStream(InputStream inputStream) throws IOException {
Reader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
while ( (line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
1.ClassPathResource
ClassPathResource 是以classes目录为根目录进行查找,开头可以带 / 也可以不带
@Test
public void classPathResource() throws IOException {
Resource resource = new
ClassPathResource("com/fll/start/resource_loader/InputResourceTest.class");
InputStream inputStream = resource.getInputStream();
printStream(inputStream);
}
读取到了InputResourceTest.class的内容
@Test
public void classPathResource1() throws IOException {
Resource resource = new ClassPathResource("beans.xml");
InputStream inputStream = resource.getInputStream();
printStream(inputStream);
}
读取到了beans.xml的内容
2. FileSystemResource
FileSystemResource 是根据资源在磁盘上的绝对路劲进行加载的
@Test
public void fileSystemResource() throws IOException {
Resource resource = new FileSystemResource("D:\\IdeaProjects\\study-spring\\target\\classes\\beans.xml");
InputStream inputStream = resource.getInputStream();
printStream(inputStream);
}
成功加载到了beans.xml
3.PathResource
PathResource 和 FileSystemResource 有点类似可以按照磁盘绝对路劲加载资源,不同的是,PathResource是可以支持按照相对路径加载资源
按照绝对路径进行加载
@Test
public void pathResource() throws IOException {
PathResource pathResource = new PathResource("D:\\IdeaProjects\\study-spring\\target\\classes\\com/fll/start/resource_loader/InputResourceTest.class");
InputStream inputStream = pathResource.getInputStream();
printStream(inputStream);
}
按照相对路劲进行加载
@Test
public void relativePathResource() throws IOException {
PathResource pathResource = new PathResource("D:/IdeaProjects/study-spring/target/classes/com/fll/start/resource_loader/InputResourceTest.class");
Resource relative = pathResource.createRelative("../DefaultResourceLoaderTest.class");
InputStream inputStream = relative.getInputStream();
printStream(inputStream);
}
@Test
public void relativePathResource1() throws IOException {
PathResource pathResource = new PathResource("D:/IdeaProjects/study-spring/target/classes/com/fll/start/resource_loader/InputResourceTest.class");
Resource relative = pathResource.createRelative("../../../../../beans.xml");
InputStream inputStream = relative.getInputStream();
printStream(inputStream);
}
都可以成功的加载到对应的资源
4.UrlResource
UrlResource 可以用来加载 网络上的相关资源
@Test
public void urlResource() throws IOException {
Resource resource = new UrlResource("https://www.baidu.com");
InputStream inputStream = resource.getInputStream();
printStream(inputStream);
}