@ActiveProfiles的值未被分配给配置文件

3

如果我将它们设置为VM参数,我的活动配置文件可以正常工作。

我想使用@ActiveProfiles("local")进行测试。

这是我正在使用的类注释:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/jpaContext.xml")
@ActiveProfiles("local")
public class MyServiceTest {

当我尝试运行时,跟踪中出现以下内容:
Caused by: java.io.FileNotFoundException: class path resource [properties/database-configuration-${spring.profiles.active}.properties] cannot be opened because it does not exist

有什么想法,为什么这个值没有被使用?

1个回答

5
当您在配置文件中解析spring.profiles.active的占位符值时,Spring将默认使用系统属性来获取该值,并在将其设置为系统属性时获取该值。
现在,在您的测试中,由于未设置此系统属性,占位符无法得到干净的解析。一种解决方法是通过bean概要文件以稍微不同的方式加载属性:
<beans profile="local">
    <context:property-placeholder location="classpath:database-config-local.properties"/>
</beans>

<beans profile="dev">
    <context:property-placeholder location="classpath:database-config-dev.properties"/>
</beans>

4
问题在于@ActiveProfiles注解不会在Environment中设置spring.profiles.active属性(它只是设置活动配置文件,这是不同的)。如果你不想按建议更改配置,你可以在测试中添加一个ApplicationContextInitializer(在@ContextConfiguration中),它会添加一个带有活动配置文件键的属性源。 - Dave Syer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接