[英]Load resource/file from test/resources using Spring
是否可以使用@Value
從 Maven 的 test/resources 目錄加載文件/資源?
例如這樣的:
@Value("${test/resources/path/to/file}") File file
編輯:
我試過這個:
@Value("${someFile}") FileSystemResource file;
但在運行時我看到它代表工作目錄而不是 test/resources 中的文件
測試/資源中的任何內容都會在測試階段之前復制到目標/測試類。 這些復制的資源將在類路徑中可用。
如果您在測試類中啟動 Spring 配置,則類路徑資源的綁定允許您像這樣注入它們:
@Value("classpath:path/to/file")
Resource resourceFile;
不需要文件,因為它也可以來自類路徑上的 jar 文件,但您可以通過 InputStream 等讀取它。
不確定是否有直接的方法可以做到這一點。
這是我們用來通過構造函數初始化它的替代方法:
@RestController
public class FileController {
private File file;
public FileController(@Value("${file-name}") String filename) {
file = new File(filename);
}
}
您可以使用ResourceUtils
加載文件。
示例: File certFile = ResourceUtils.getFile("classpath:certs/cert.txt");
然后您可以使用InputStream
處理它,如下所示: InputStream inputStream = new FileInputStream(certFile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.