Spring Boot
Java
Port Configuration
Application Development
Programming Tutorial

Spring Boot - How to get the running port

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring Boot is a framework widely used in Java environments to simplify the development of new Spring applications. It takes an opinionated view, which means it comes with default configurations that help developers build applications faster. However, despite these default configurations, there are times when understanding and control of the application's running parameters, such as the server port, are essential. This article will explore various methods to determine and manage the port on which a Spring Boot application is running.

Understanding Spring Boot's Default Port

By default, Spring Boot applications start on port 8080. This is because Spring Boot comes with an embedded Tomcat server whose default configuration includes listening on port 8080. However, developers often need to identify or change this port due to port conflicts or specific deployment requirements.

How to Get the Running Port

To get the running port of a Spring Boot application programmatically, you can use different approaches.

Accessing the Port via application.properties or application.yml

Spring Boot allows the configuration of the server port using its properties files.

  • application.properties:
 
  server.port=8081
  • application.yml:
yaml
  server:
    port: 8081

You can read the specified port from these configuration files. However, if you need to dynamically retrieve the current running port at runtime, you can leverage the EmbeddedWebServer interface.

Using EmbeddedWebServer to Retrieve the Port at Runtime

Spring Boot provides mechanisms for retrieving the actual running port when the port is dynamically set by the operating system (e.g., port 0, which tells the OS to use any available port).

Here's how you can do it:

  1. Implement a Bean that listens when the application starts.
java
1   import org.springframework.boot.web.context.WebServerApplicationContext;
2   import org.springframework.stereotype.Component;
3
4   @Component
5   public class ServerPortListener {
6
7       private final WebServerApplicationContext webServerAppCtxt;
8
9       public ServerPortListener(WebServerApplicationContext webServerAppCtxt) {
10           this.webServerAppCtxt = webServerAppCtxt;
11       }
12
13       public int getServerPort() {
14           return webServerAppCtxt.getWebServer().getPort();
15       }
16   }
  1. Use this Bean within your application to access the running port.

Retrieving the Port via Spring's Environment

Another approach is to retrieve the port using Spring's Environment.

java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.core.env.Environment;
3import org.springframework.stereotype.Component;
4
5@Component
6public class ServerPortService {
7
8    @Autowired
9    private Environment environment;
10
11    public String getServerPort() {
12        return environment.getProperty("local.server.port");
13    }
14}

This method is effective when the port may change at runtime or be overridden in different environments.

Changing the Default Port

Changing Spring Boot's default port is quite straightforward. This can be done using multiple approaches:

  1. Properties and YAML Files: As stated earlier, change server.port in application.properties or application.yml.
  2. Command Line Argument: Use -Dserver.port=9090 when running the JAR file.
  3. Programmatically in a SpringApplication:
java
1   import org.springframework.boot.SpringApplication;
2   import org.springframework.boot.autoconfigure.SpringBootApplication;
3   import org.springframework.boot.web.server.WebServerFactoryCustomizer;
4   import org.springframework.boot.web.server.ConfigurableWebServerFactory;
5   import org.springframework.context.annotation.Bean;
6   
7   @SpringBootApplication
8   public class Application {
9   
10       public static void main(String[] args) {
11           SpringApplication.run(Application.class, args);
12       }
13   
14       @Bean
15       public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
16           return factory -> factory.setPort(9090);
17       }
18   }

Summary Table

MethodDescriptionExample Usage
application.properties / ymlSet server.port in the configuration files.server.port=8081 In YAML: Server block
EmbeddedWebServer InterfaceProgrammatically access the running port.Use WebServerApplicationContext
Environment PropertyRetrieve port through Spring's Environment.environment.getProperty("local.server.port")
Command LineOverride the port during application start.-Dserver.port=9090
WebServerFactoryCustomizerCustomize the port programmatically on startup.Override WebServerFactoryCustomizer

Conclusion

Understanding how to retrieve and configure the running port of a Spring Boot application is essential for various development and deployment scenarios. Whether via configuration files, dynamic runtime values, or programmatically setting values, developers have multiple flexible options to manage server ports in Spring Boot applications. This versatility not only simplifies debugging and development but also streamlines deployment in diverse environments.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.