Spring Doc - Resources

2.1. Introduction

Java 标准的 URL 类和各种 URL 前缀的标准处理器,还不能完全满足访问low-level 的资源。

2.2. The Resource Interface

Spring 的 Resource 接口位于 org.springframework.core.io. 包下,是一个更强大的接口,用于抽象对 low-level 资源的访问。

public interface Resource extends InputStreamSource {
    boolean exists();
    boolean isReadable();
    boolean isOpen();
    boolean isFile();
    URL getURL() throws IOException;
    URI getURI() throws IOException;
    File getFile() throws IOException;
    ReadableByteChannel readableChannel() throws IOException;
    long contentLength() throws IOException;
    long lastModified() throws IOException;
    Resource createRelative(String relativePath) throws IOException;
    String getFilename();
    String getDescription();
}

2.3. Built-in Resource Implementations

2.3.1. UrlResource

UrlResource 包装了 java.net.URL,可用于访问通常可通过 URL 访问的任何对象,例如文件、HTTPS 目标、FTP 目标等。

2.3.2. ClassPathResource

此类表示应从类路径获得的资源。它使用线程上下文类加载器、给定类加载器或给定类来加载资源。

2.3.3. FileSystemResource

这个类是用来处理 java.io.File 的,它也支持 java.nio.file.path 处理。

2.3.4. PathResource

这个类支持 java.nio.file.path 资源的操作。

2.3.5. ServletContextResource

这个实现类用于处理 ServeletContext 资源,即 web 应用的 root 目录文件。

2.3.6. InputStreamResource

用来处理给定 InputStream 的资源处理类。

2.3.7. ByteArrayResource

用来处理给定 byte array 的资源处理类。

2.4. The ResourceLoader Interface

ResourceLoader 接口的实现类可以返回一个 resource 对象。

public interface ResourceLoader {
    Resource getResource(String location);
    ClassLoader getClassLoader();
}

所有 application contexts 都实现 ResourceLoader 接口。因此,可以使用所有 application contexts 来获取资源实例。

2.5. The ResourcePatternResolver Interface

ResourcePatternResolver 接口是对ResourceLoader 接口的扩展,它定义把位置模式解析为资源对象的策略。

public interface ResourcePatternResolver extends ResourceLoader {
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
    Resource[] getResources(String locationPattern) throws IOException;
}

2.6. The ResourceLoaderAware Interface

ResourceLoaderAware 是一个回调接口,用于标识预期提供 ResourceLoader 引用的组件。

public interface ResourceLoaderAware {
    void setResourceLoader(ResourceLoader resourceLoader);
}

2.7. Resources as Dependencies

如果 bean 本身要通过某种动态过程来确定和提供资源路径,那么 bean 使用 ResourceLoader 或 ResourcePatternResolver 接口来加载资源可能是有意义的。

2.8. Application Contexts and Resource Paths

2.8.1. Constructing Application Contexts

一个 application context 构造方法一般需要一个字符串或者字符串数组作为资源的地址。

ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

2.8.2. Wildcards in Application Context Constructor Resource Paths

使用通配符。

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml");

2.8.3. FileSystemResource Caveats

A FileSystemResource that is not attached to a FileSystemApplicationContext treats absolute and relative paths as you would expect.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章