Port 0 asks the OS for a free port, which is how integration tests avoid clashing.
// application.yml
server:
port: 8080
servlet:
context-path: /api
// In a test:
@SpringBootTest(webEnvironment = RANDOM_PORT)
class ApiTest {
@LocalServerPort int port;
}
Tomcat started on port 8080 (http) with context path '/api'
In tests: a different free port every run, injected into the field.
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11