@Value("${local.server.port}") 在 Spring Boot 1.5 中不起作用

Mee*_*ary 7 java spring spring-boot spring-boot-test

我正在将 Spring Boot 从 1.3 升级到 1.5。为了升级到 1.5 我已经更换了

@SpringApplicationConfiguration(classes = TestConfig.class) @WebIntegrationTest

@SpringBootTest(classes = TestConfig.class)

另外,我正在使用

@Value("${local.server.port}") protected int port;

获取application.properties文件中定义的端口号。我进一步使用这个端口号来构建一个 REST URL。

但是升级后我收到以下错误,而1.3Spring Boot Test也可以正常工作。

引起:java.lang.IllegalArgumentException:无法在 org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) 处解析值“${local.server.port}”中的占位符“local.server.port”

我是否错过了为此工作所需的任何更改。

new*_*wur 8

您必须为 提供一个值webEnvironment。在你的情况下DEFINED_PORT像这样

@SpringBootTest(classes = App.class, webEnvironment = WebEnvironment.DEFINED_PORT)
public class YourTest {

  @LocalServerPort           // shorthand for @Value("${local.server.port}")
  private Integer port;
  ...
}
Run Code Online (Sandbox Code Playgroud)

详情见:https : //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications


小智 0

首先确保属性文件中的属性拼写正确。正如我几天前使用 spring-boot-1.5.2 所做的那样,它有效。

或者

你需要添加

@PropertySource(“类路径:application.properties”)

到你的班级,所以它会选择你的配置。

如果您需要不同的配置进行测试,您可以添加

@TestPropertySource(locations="classpath:test.properties")

参考@Value 在 Spring Boot 测试中不起作用