【发布时间】:2018-08-03 21:08:57
【问题描述】:
我正在使用 Spring Boot 开发应用程序。我在文件系统上有一个外部化的属性文件。它的位置存储在一个环境变量中,如下所示--
export props=file://Path-to-file-on-filesystem/file.properties
此文件中的属性加载到类路径中,并可供应用程序使用,如下所示--
List<String> argList = new ArrayList<>();
String properties = System.getenv().get("props");
try (InputStream is = BinaryFileReaderImpl.getInstance().getResourceAsStream(properties)) {
if (is != null) {
Properties props = new Properties();
props.load(is);
for(String prop : props.stringPropertyNames()) {
argList.add("--" + prop + "=" + props.getProperty(prop));
}
}
} catch(Exception e) {
//exception handling
}
这个 argList 被传递给SpringBootApplication,当它像下面这样开始时--
SpringApplication.run(MainApplication.class, argList);
我可以使用${prop.name}访问所有属性
但是,当我运行 JUnit 集成测试时,我无权访问这些属性。我所有的数据库属性都在这个外部属性文件中。我不想将此文件保留在应用程序中的任何位置,例如。 src/main/resources
有什么方法可以在 spring 的测试上下文中加载这些属性?
【问题讨论】:
-
您是否在测试中尝试过
@PropertySource注释? -
是的,我已经尝试过
@PropertySource({"file:${props}"),正如提到的here。它在 Windows 上不起作用。没有在 Linux 上尝试过。
标签: spring spring-boot junit properties properties-file