70.4 Discover the HTTP port at runtime

You can access the port the server is running on from log output or from the EmbeddedWebApplicationContext via its EmbeddedServletContainer. The best way to get that and be sure that it has initialized is to add a @Bean of type ApplicationListener<EmbeddedServletContainerInitializedEvent> and pull the container out of the event when it is published.

Tests that use @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) can also inject the actual port into a field using the @LocalServerPort annotation. For example:

_@RunWith(SpringJUnit4ClassRunner.class)_
_@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)_
public class MyWebIntegrationTests {

    _@Autowired_
    EmbeddedWebApplicationContext server;

    _@LocalServerPort_
    int port;

    // ...

}
[Note] Note
@LocalServerPort is a meta-annotation for @Value("${local.server.port}"). Don’t try to inject the port in a regular application. As we just saw, the value is only set once the container has initialized; contrary to a test, application code callbacks are processed early (i.e. before the value is actually available).

results matching ""

    No results matching ""