Is it possible to inject the contents of a file on classpath to a member variable upon construction of the corresponding class?
@Component
public class MyClass {
@Value("classpath:my_file.txt")
private String myFile;
}
Is it possible to inject the contents of a file on classpath to a member variable upon construction of the corresponding class?
@Component
public class MyClass {
@Value("classpath:my_file.txt")
private String myFile;
}
There is the annotation @Value, but it will inject a Resource, not its contents.
But once you have the resource, you can easily read its contents with class StreamUtils as below:
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);
}
}
Sure
import org.springframework.core.io.Resource;
@Value("classpath:my_file.txt")
private Resource myFile;