[英]Inject File from classpath using Spring Environment
我的問題:如何使用Environment
變量在我的類中注入一個File
?
我在properties
指定了我需要讀取的文件的路徑:
myFile.path=classpath:myFile.json
我曾經有一個XML應用程序上下文定義了properties.file
的property-placeholder
,然后我可以使用@Value
注入我的文件:
@Value("${myFile.path}")
private File myFile;
然而,現在我想做一些事情:
@Inject
private Environment environment;
private File myFile;
@PostConstruct
private void init() {
myFile = environment.getProperty("myFile.path", File.class);
}
但拋出異常:
Caused by: java.io.FileNotFoundException:
classpath:myFile.json (No such file or directory)
我也試過像myFile = environment.getProperty("myFile.path", Resource.class).getFile();
但拋出了另一個例外。
知道屬性中定義的路徑可以是絕對路徑還是類路徑相對,我如何實現注入文件?
您可以嘗試注入ResourceLoader
,並使用它來加載引用的類路徑資源:
@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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.