Spring Boot: The embedded server port and context path

Port 0 asks the OS for a free port, which is how integration tests avoid clashing.

Code
// application.yml
server:
  port: 8080
  servlet:
    context-path: /api

// In a test:
@SpringBootTest(webEnvironment = RANDOM_PORT)
class ApiTest {
    @LocalServerPort int port;
}
Output
Tomcat started on port 8080 (http) with context path '/api'
In tests: a different free port every run, injected into the field.
Advertisement

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