如何使外部化属性文件可用于 spring 启动集成测试?
How to make externalized properties file available to spring boot integration tests?
我正在使用 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 的测试上下文中加载这些属性?
我终于可以在 linux 机器上使用 @PropertySource
读取外部化属性文件。虽然无法在 Windows 实例上运行。
修改如下-
export props=/path-to-file
请注意,file://
和实际文件名已从环境变量中删除。
@Configuration
@PropertySource({"file:${props}/file-test.properties", "classpath:some_other_file.properties"})
public class TestConfiguration {
}
将此配置 class 保存在各个项目的 src/test/java 文件夹中。谢谢 Joe Chiavaroli 上面的评论。
我正在使用 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 的测试上下文中加载这些属性?
我终于可以在 linux 机器上使用 @PropertySource
读取外部化属性文件。虽然无法在 Windows 实例上运行。
修改如下-
export props=/path-to-file
请注意,file://
和实际文件名已从环境变量中删除。
@Configuration
@PropertySource({"file:${props}/file-test.properties", "classpath:some_other_file.properties"})
public class TestConfiguration {
}
将此配置 class 保存在各个项目的 src/test/java 文件夹中。谢谢 Joe Chiavaroli 上面的评论。