目录
1、ResourceLoader 介绍
ResourceLoader接口用于返回 Resource 对象;其实现可以看作是一个生产Resource的工厂类。
Spring提供了一个适用于所有环境的DefaultResourceLoader实现,可以返回ClassPathResource、UrlResource;还提供一个用于web环境的ServletContextResourceLoader,它继承了DefaultResourceLoader的所有功能,又额外提供了获取ServletContextResource的支持。
ResourceLoader在进行加载资源时需要使用前缀来指定需要加载:“classpath:path”表示返回ClasspathResource,“http://path”和“file:path”表示返回UrlResource资源,如果不加前缀则需要根据当前上下文来决定,DefaultResourceLoader默认实现可以加载classpath资源。
ResourceLoader 源码:
package org.springframework.core.io;
import org.springframework.lang.Nullable;
public interface ResourceLoader {
String CLASSPATH_URL_PREFIX = "classpath:";
// 用于根据提供的location参数返回相应的Resource对象
Resource getResource(String var1);
// 返回加载这些Resource的ClassLoader
@Nullable
ClassLoader getClassLoader();
}
2、Resource 介绍
Spring中用 Resource 接口封装底层资源,统一管理。Resource实现有:文件(FileSystemResource)、ClassPath资源(ClassPathResource)、URL资源(URLResource)、InputStream资源(InputStreamResource)、Byte数组(ByteArrayResource)等。
参考:Spring源码解析系列文章(三)——DefaultListableBeanFactory、XmlBeanFactory
Resource源码:
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.springframework.lang.Nullable;
public interface Resource extends InputStreamSource {
boolean exists();
default boolean isReadable() {
return this.exists();
}
default boolean isOpen() {
return false;
}
default boolean isFile() {
return false;
}
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
default ReadableByteChannel readableChannel() throws IOException {
return Channels.newChannel(this.getInputStream());
}
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String var1) throws IOException;
@Nullable
String getFilename();
String getDescription();
}
来源:CSDN
作者:ruanhao1203
链接:https://blog.csdn.net/ruanhao1203/article/details/103493017