我有一个主要的 app-context.xml,它定义了一个具有两个位置的属性占位符:默认属性文件和一个可选的覆盖文件:
<context:property-placeholder
location="classpath:config.properties,${configOverride}"
ignore-resource-not-found="true" />
可选的覆盖位置允许指定另一个属性文件(例如“-DconfigOverride=file:/home/app/config.properties”),其中仅包含应覆盖的属性。
对于我的单元测试,我使用了导入 app-context.xml 的测试上下文:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class UserServiceTest {
...
}
如何在加载应用程序上下文之前在应用程序中设置系统属性或环境变量?如果可能的话,我想在所有测试类中实现与设置“-DconfigOverride=classpath:testConfig.properties”相同的效果,而无需指定命令行参数。
最佳答案
另一种选择是在 @BeforeClass 注释方法中设置环境属性,该方法将在上下文配置发生之前调用。
@BeforeClass
public static void setSystemProps() {
System.setProperty("configOverride", "yourVal");
}
关于java - 使用 SpringJunit4ClassRunner 在属性占位符之前设置系统属性或环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822010/