使用 Spring 从 test/resources 加载 resource/file

Load resource/file from test/resources using Spring

是否可以使用 @Value 从 Maven 的 test/resources 目录加载 File/Resource?

例如像这样:

@Value("${test/resources/path/to/file}") File file 

编辑:

我试过这个:

@Value("${someFile}") FileSystemResource file;

但在运行时我看到它代表工作目录而不是 test/resources

中的文件

不确定是否有直接的方法来做到这一点。

这是我们通过构造函数初始化它的替代方法:

@RestController
public class FileController {

    private File file;

    public FileController(@Value("${file-name}") String filename) {
        file = new File(filename);
    }

}

test/resources 中的任何内容都将在测试阶段之前复制到 target/test-classes。这些复制的资源将在类路径中可用。

如果您在测试 类 中启动 Spring 配置,则存在类路径资源的绑定,允许您像这样注入它们:

   @Value("classpath:path/to/file")
   Resource resourceFile;

不需要文件,因为它也可以来自类路径上的 jar 文件,但您可以通过 InputStream 等读取它。