Reputation: 86905
I want to inject a file from src/main/resources
like this:
@Value("classpath:myfile.txt")
private Resource res;
When I run this from eclipse it works fine. But from a standalone folder, the file is not found:
Caused by: java.io.FileNotFoundException: class path resource [myfile.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/myapp/myapp-1.0.0.jar!/myfile.txt
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:212) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
How can I tell spring that the file to be injected is actually in the root of the jar, not an absolute path?
Same result if I try to load it programmatically.
res = new ClassPathResource("myfile.txt");
Upvotes: 3
Views: 2525
Reputation: 32086
You said this works in eclipse:
@Value("classpath:myfile.txt")
private Resource res;
Now try this in eclipse (notice the *
), if it works, standalone should be ok:
@Value("classpath*:myfile.txt")
private Resource res;
When deploying outside eclipse, make sure myfile.txt
is on the classpath; the best location is in the root directory where Java class file packages are located (com
, org
)
Upvotes: 1
Reputation: 86905
It turned out the injection itself did work, BUT I accessed the file using res.getFile()
which threw the NPE.
When just retrieving the URL and fetching the file explicit with File file = ResourceUtils.getFile(res.getURL().getFile());
it worked as expected.
Though I'm not sure wether this is a bug or works as expected.
Upvotes: 1