My problem: how can I inject a File
in my class using the Environment
variable?
I specify in a properties
the path of a file I need to read:
myFile.path=classpath:myFile.json
I used to have an XML application context defining a property-placeholder
for that properties.file
and then I simply could inject my file using the @Value
:
@Value("${myFile.path}")
private File myFile;
Yet, now I'd like to do something like:
@Inject
private Environment environment;
private File myFile;
@PostConstruct
private void init() {
myFile = environment.getProperty("myFile.path", File.class);
}
But an Exception is thrown:
Caused by: java.io.FileNotFoundException:
classpath:myFile.json (No such file or directory)
I also tried something like myFile = environment.getProperty("myFile.path", Resource.class).getFile();
but an other exception is thrown.
How can I achieve to inject my file knowing that the path defined in the properties can be absolute or classpath relative?
You can try injecting the ResourceLoader
, and use it to load the referenced classpath resource:
@Autowired
private ResourceLoader resourceLoader;
...
@PostConstruct
private void init() {
String resourceReference = environment.getProperty("myFile.path");
Resource resource = resourceLoader.getResource(resourceReference);
if (resource != null) {
myFile = resource.getFile();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.