【问题标题】:Spring - inject contents of file from classpath into annotated memberSpring - 将文件内容从类路径注入带注释的成员
【发布时间】:2017-02-28 18:56:17
【问题描述】:

是否可以在构造相应的类时将类路径上的文件内容注入成员变量?

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

【问题讨论】:

标签: java spring dependency-injection annotations java-io


【解决方案1】:

有注解@Value,但它会注入一个Resource,而不是它的内容。

但是一旦你有了资源,你就可以通过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);
    }
}

【讨论】:

    【解决方案2】:

    当然

    import org.springframework.core.io.Resource;
    
    @Value("classpath:my_file.txt")
    private Resource myFile;
    

    【讨论】:

    • 资源不是字符串!
    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多