我正在使用System属性来定义特定于环境的属性文件的位置。但是,我想将该值覆盖为集成测试的不同值。
这是我的生产弹簧设置。我正在使用自定义的PropertyPlaceholderConfigurer来解析一些加密的属性文件值,但这在这里并不重要:
<-- Spring configuration in file service-spring-beans.xml -->
<bean class="com.mycompany.MyPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/${MY_ENVIRONMENT}/${MY_ENVIRONMENT}.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="false"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
在运行时,我们将MY_ENVIRONMENT的值定义为Java系统属性。这一切都按预期工作。但是,对于集成测试,我想将MY_ENVIRONMENT定义为“inttest”,因此会加载特定于集成测试的属性文件属性/ inttest / inttest.properties。
我尝试使用Integration-test加载的spring上下文来设置ID为MY_ENVIRONMENT的String bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.mycompany.myclasses"/>
<bean class="java.lang.String" id="MY_ENVIRONMENT">
<constructor-arg value="inttest"/>
</bean>
<!-- this imports the production spring context -->
<import resource="classpath:service-spring-beans.xml"/>
</beans>
但是,MY_ENVIRONMENT的值未解决,运行集成测试时出现此错误。
引起: org.springframework.beans.factory.BeanInitializationException:可以 不加载属性;嵌套异常是 java.io.FileNotFoundException:类路径资源 [properties / $ {MY_ENVIRONMENT} / $ {MY_ENVIRONMENT} .properties]不能 因为它不存在而被打开
如何在没有将System属性传递给JVM的情况下在最近时覆盖MY_ENVIRONMENT?
答案 0 :(得分:3)
由于我使用maven surefire插件来运行集成测试,最简单的解决方案是使用surefire插件配置来设置系统属性,如下所示:
<configuration>
<systemPropertyVariables>
<MY_ENVIRONMENT>inttest</MY_ENVIRONMENT>
</systemPropertyVariables>
<!-- ... -->
<configuration>
答案 1 :(得分:2)
由于您不想使用配置文件,因此您可以创建多个上下文,并根据需要包含适当的上下文文件。因此,对于集成测试,您拥有application-context.xml和integration-property-context.xml文件,而在prod环境中,您将application-context.xml包含在production-property-context.xml文件中。我已经看到这种方法大量用于在dev和prod之间切换数据源,其中dev是BasicDataSource实现,prod环境引用JDNI DataSource。
这种方法可以帮助您避免使用ActiveProfile,但是您可能会遇到管理重复bean的问题,而ActiveProfiles可能会真正简化这些问题。
答案 2 :(得分:1)
您可以查看使用活动配置文件覆盖整个属性占位符实现。也就是说,默认(无配置文件)启动您的属性占位符,但测试配置文件(例如'test')可以为属性占位符创建一个新的测试bean。
属性占位符的一个挑战是它在应用程序上下文启动的最初阶段加载,因此普通的覆盖bean可能无效。