1. 程式人生 > 程式設計 >Spring系列八:Spring 中讀取檔案-ResourceLoaderAware

Spring系列八:Spring 中讀取檔案-ResourceLoaderAware

重疊淚痕緘錦字,人生只有情難死。

概述

本文將瞭解資源或檔案(例如文字檔案、XML檔案、屬性檔案或影象檔案)載入到Spring應用程式上下文中的不同實現。Spring ResourceLoader為我們提供了一個統一的getResource()方法來通過資源路徑檢索外部資源。

資源(Resource)介面

ResourceSpring中用於表示外部資源的通用介面。

SpringResource介面提供了以下6種實現。

  1. UrlResource
  2. ClassPathResource
  3. FileSystemResource
  4. ServletContextResource
  5. InputStreamResource
  6. ByteArrayResource

我們可以指定不同的字首來建立路徑以從不同位置載入資源

字首 示例 說明
classpath: classpath:com/myapp/config.xml 從類路徑載入
file: file:///data/config.xml 從檔案系統作為URL載入。
http: https://myserver/logo.png URL載入
(none) /data/config.xml 取決於底層的ApplicationContext

ResourceLoader

它用於載入資源(例如類路徑或檔案系統資源)。它有兩種方法:

//Expose the ClassLoader used by this ResourceLoader.
ClassLoader getClassLoader() //Return a Resource handle for the specified resource location. Resource getResource(String location) 複製程式碼

getResource()方法將根據資源路徑決定要例項化的Resource實現。 要獲取ResourceLoader的引用,請實現ResourceLoaderAware介面。

Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt"
); 複製程式碼

使用ApplicationContext載入資源

Spring中,所有應用程式上下文都實現ResourceLoader介面。因此,所有應用程式上下文都可用於獲取資源例項。

要獲取ApplicationContext的引用,請實現ApplicationContextAware介面。

Resource banner = ctx.getResource("file:c:/temp/filesystemdata.txt");
複製程式碼

使用ResourceLoaderAware載入資源

為了演示下面的各種示例,我將一個具有相同名稱的檔案放置在不同的位置,並且我將演示如何載入每個檔案。

CustomResourceLoader.java的編寫如下,它將已載入的資原始檔的內容列印到控制檯中。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
 
public class CustomResourceLoader implements ResourceLoaderAware
{
    private ResourceLoader resourceLoader;
 
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
 
    public void showResourceData() throws IOException
    {
        //This line will be changed for all versions of other examples
        Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
 
        InputStream in = banner.getInputStream();
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
 
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        reader.close();
    }
}

複製程式碼

該檔案的applicationContext.xml檔案條目如下:

<bean id="customResourceLoader" class="cn.howtodoinjava.demo.CustomResourceLoader"></bean>
複製程式碼

為了測試CustomResourceLoader bean並呼叫showResourceData()方法,使用了以下程式碼:

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception
{
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
    CustomResourceLoader customResourceLoader = (CustomResourceLoader) context.getBean("customResourceLoader");
 
    customResourceLoader.showResourceData();
}
複製程式碼

https://user-gold-cdn.xitu.io/2019/10/25/16e007f0502c5381?w=336&h=268&f=png&s=3933
https://user-gold-cdn.xitu.io/2019/10/25/16e007f0502c5381?w=336&h=268&f=png&s=3933

由於我們正在通過Spring的資源載入器訪問資源,因此自定義資源載入器必須實現ApplicationContextAware介面或ResourceLoaderAware介面。

載入外部資源

從應用程式根資料夾載入資源

要從應用程式資料夾載入檔案,請使用以下模板:

Resource banner = resourceLoader.getResource("file:data.txt");
複製程式碼

從類路徑載入資源

要從類路徑載入檔案,請使用以下模板:

Resource banner = resourceLoader.getResource("classpath:classpathdata.txt");
複製程式碼

從檔案系統載入資源

要從應用程式資料夾外部的檔案系統載入檔案,請使用以下模板:

Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
複製程式碼

URL載入資源

要從任何URL載入檔案,請使用以下模板:

Resource banner = resourceLoader.getResource("//howtodoinjava.com/readme.txt");
複製程式碼

以上所有示例將從其位置載入資原始檔,你可以按需要使用它們。

如何注入外部檔案

在上面的示例中,我們在CustomResourceLoader中對資源名稱進行了硬編碼,很多人可能不喜歡它,並且希望通過上下文件案對其進行配置。使用下面的程式碼模板可以配置外部資源名稱。

<bean id="customResourceLoader" class="com.howtodoinjava.demo.CustomResourceLoader">
 
    <property name="resource">
        <value>classpath:classpathdata.txt</value>
        <!-- or -->
        <value>file:data.txt</value>
    </property>
 
</bean>
複製程式碼

CustomResourceLoader如下所示:

public class CustomResourceLoader {
 
    private Resource resource;
 
    public Resource getResource() {
        return resource;
    }
 
    public void setResource(Resource resource) {
        this.resource = resource;
    }
}
複製程式碼

在上下文初始化後,資源將注入到CustomResourceLoaderresource屬性中。在Spring Boot Resourceloader示例中也可以使用相同的程式碼。

原文連結:Spring ResourceLoaderAware – Read file in Spring