How do I configure the TCP/IP port listened on by a Spring Boot application, so it does not use the default port of 8080.
To extend other answers:
There is a section in the docs for testing which explains how to configure the port on integration tests:
At integration tests, the port configuration is made using the annotation @SpringBootTest
and the webEnvironment
values.
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
You can inject the value using @LocalServerPort
which is the same as @Value("${local.server.port}")
.
Random port test configuration:
@RunWith(SpringRunner.class
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ExampleTest {
...
@LocalServerPort //to inject port value
int port;
}
@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)
It takes the value from server.port
if is defined.
@TestPropertySource(properties = "server.port=9192")
, it overrides other defined values.src/test/resources/application.properties
(if exists). 8080
.Example:
Defined port test configuration:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = "server.port=9192")
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}