如何使用Spring配置文件表达式?

时间:2018-09-05 10:41:51

标签: spring spring-boot

Spring Boot: 2.0.4.RELEASE

我已经指定了Spring Boot multi-profile YAML配置文件:

server:
        address: 192.168.1.100
---
spring:
        profiles: development
server:
        address: 127.0.0.1
---
spring:
        profiles: production | eu-central
server:
        address: 192.168.1.120

根据reference guide,如果production eu-central配置文件处于活动状态,则server.address属性为192.168.1.120。但是当我运行此测试

@ActiveProfiles({"production"})
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProfileTest {

  @Autowired
  private Environment environment;
  @Value("${server.address}")
  private String serverAddress;

  @Test
  public void testProfile() {
    assertThat(environment.getActiveProfiles(), is(new String[] {"production"} ));
    assertThat(serverAddress, is("192.168.1.120"));
  }

}

失败:

java.lang.AssertionError: 

Expected: is "192.168.1.120"
     but: was "192.168.1.100"
        at com.example.demo.ProfileTest.testProfile(ProfileTest.java:27)

为什么测试失败,如何正确使用Spring配置文件表达式? 顺便说一句,如果我从 | eu-central键中删除了spring.profiles,则测试通过!

1 个答案:

答案 0 :(得分:2)

鲍里斯。我研究了你的问题。而且我认为我在Spring-boot中发现了一个错误。我报告了一个问题,因此您可以检查它。问题是SpringBoot始终使用$ {server.address}的默认值,因为框架无法识别配置文件: eu-central作为配置文件列表。如果我使用

@ActiveProfiles(value = "production | eu-central")

一切正常。

此处https://github.com/spring-projects/spring-boot/issues/14314

关于Spring-boot的链接

因此,您可以看到讨论。 谢谢!

已更新

我已经从Spring Team得到了关于我问题的答案。

  

此格式是Spring Framework 5.1(因此是Spring Boot 2.1)   功能)。

所以您的问题的答案是 此功能将在Spring Boot 2.1中提供。