【发布时间】: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
是否可以在构造相应的类时将类路径上的文件内容注入成员变量?
@Component
public class MyClass {
@Value("classpath:my_file.txt")
private String myFile;
}
【问题讨论】:
标签: java spring dependency-injection annotations java-io
有注解@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);
}
}
【讨论】:
当然
import org.springframework.core.io.Resource;
@Value("classpath:my_file.txt")
private Resource myFile;
【讨论】: