Spring Boot - How to get the running port Spring Boot - How to get the running port spring spring

Spring Boot - How to get the running port


Is it also possible to access the management port in a similar way, e.g.:

  @SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)  public class MyTest {    @LocalServerPort    int randomServerPort;    @LocalManagementPort    int randomManagementPort;


Spring's Environment holds this information for you.

@AutowiredEnvironment environment;String port = environment.getProperty("local.server.port");

On the surface this looks identical to injecting a field annotated @Value("${local.server.port}") (or @LocalServerPort, which is identical), whereby an autowiring failure is thrown at startup as the value isn't available until the context is fully initialised. The difference here is that this call is implicitly being made in runtime business logic rather than invoked at application startup, and hence the 'lazy-fetch' of the port resolves ok.


Thanks to @Dirk Lachowski for pointing me in the right direction. The solution isn't as elegant as I would have liked, but I got it working. Reading the spring docs, I can listen on the EmbeddedServletContainerInitializedEvent and get the port once the server is up and running. Here's what it looks like -

import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;    @Component    public class MyListener implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {      @Override      public void onApplicationEvent(final EmbeddedServletContainerInitializedEvent event) {          int thePort = event.getEmbeddedServletContainer().getPort();      }    }