[英]How to inject a Resource from classpath in Spring?
我想从src/main/resources
注入一个文件,如下所示:
@Value("classpath:myfile.txt")
private Resource res;
当我从eclipse运行它时它工作正常。 但是从独立文件夹中找不到该文件:
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]
我怎么能告诉spring要注入的文件实际上是在jar的根目录中,而不是绝对路径?
如果我尝试以编程方式加载它,结果相同。
res = new ClassPathResource("myfile.txt");
你说这在eclipse中起作用:
@Value("classpath:myfile.txt")
private Resource res;
现在在eclipse中尝试这个(注意*
),如果它工作,独立应该没问题:
@Value("classpath*:myfile.txt")
private Resource res;
在eclipse之外部署时,请确保myfile.txt
在classpath上; 最佳位置位于Java类文件包所在的根目录中( com
, org
)
事实证明注入本身确实有效,但我使用res.getFile()
来访问该文件,该文件抛出了NPE。
当只检索URL并使用File file = ResourceUtils.getFile(res.getURL().getFile());
显式获取文件时File file = ResourceUtils.getFile(res.getURL().getFile());
它按预期工作。
虽然我不确定这是一个错误还是按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.