Search code examples
spring-bootspring-boot-test

Accessing @LocalServerPort in Configuration Class while running Spring Boot Test


I'm running a full SpringBoot Application using a random port in my SpringBootTest. I can retrieve the random port in my test class by using the annotation @LocalServerPort:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {MyTest.LocalConfig.class})
public class MyTest {

  @LocalServerPort
  private Integer port;

Unfortunately I cannot retrieve the random port in my Configuration class, where I want to create test beans using the random port:

  @TestConfiguration
  public static class LocalConfig {

    @Bean
    public MyBean myBean(@Value("${local.server.port}") int port) {

Here I get this error:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 
'local.server.port' in value "${local.server.port}"

Solution

  • Thanks to knoobie I've figured out this solution:

    @Lazy
    @TestConfiguration
    public static class LocalConfig {
    
      @Bean
      public MyBean myBean(@Value("${local.server.port}") int port) {
    

    If you use @Lazy, you can access the value local.server.port in the Configuration class.

    The Beans in the Lazy Configuration class will be instantiated at last, so the port is available in that phase.

    Unfortunately it is not possible to use the @Primary annotation in combination with @Lazy for overriding beans, because @Primary annotated beans are instantiated at an early phase.