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.

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