[英]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.