簡體   English   中英

Spring-將文件內容從類路徑注入到帶注釋的成員中

[英]Spring - inject contents of file from classpath into annotated member

在構造相應的類時,是否可以將類路徑上文件的內容注入到成員變量中?

@Component
public class MyClass {
    @Value("classpath:my_file.txt")
    private String myFile;
}

當然

import org.springframework.core.io.Resource;

@Value("classpath:my_file.txt")
private Resource myFile;

有注釋@Value,但是它將注入資源,而不是其內容。

但是一旦有了資源,就可以使用StreamUtils類輕松讀取其內容,如下所示:

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.StreamUtils;

@Value("classpath:/file.txt")
public void setFile(Resource myRes) throws IOException {
    try (InputStream is = myRes.getInputStream()) {
        // Content of the file as a String
        String contents = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM