@Value("${local.server.port}") not working in Spring boot 1.5

Meena Chaudhary picture Meena Chaudhary · Apr 18, 2017 · Viewed 12.4k times · Source

I am upgrading Spring Boot from 1.3 to 1.5. For upgrading to 1.5 I have replaced

@SpringApplicationConfiguration(classes = TestConfig.class) @WebIntegrationTest

with

@SpringBootTest(classes = TestConfig.class)

Also, I am using

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

to get port number defined in application.properties file. I further use this port number to build a REST URL.

But after the upgrade I am getting the error below whereas the same works fine with 1.3 Spring Boot Test.

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'local.server.port' in value "${local.server.port}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)

Am I missing any changes that I need to do for this to work.

Answer

newur picture newur · Dec 11, 2017

You have to provide a value for webEnvironment. In your case DEFINED_PORT like this

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

  @LocalServerPort           // shorthand for @Value("${local.server.port}")
  private Integer port;
  ...
}

For details see: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications