Spring Boot - Random/Dynamic Port Allocation
Last Updated :
24 Apr, 2025
Unlike the Spring MVC project where we have to manually add and install the Tomcat server, Spring Boot comes with an embedded Tomcat server, so that the applications can be hosted on it. And this Tomcat server runs on a port number and the default port number is 8080. And in the Spring Boot application, we can change the default port number in the application.properties file. Please refer to this article Spring Boot – Change Port. But what if we need a Random/Dynamic Port number? Before that let's see why we need a random/dynamic port.
Why do we need a random/dynamic port?
Sometimes we want to run multiple instances of a single app on the same server. And if you want to do this then we need to assign different ports in the run time only. And for this reason, we need to allocate random/dynamic ports at app startup. So we can do the change port in the application.properties file.
How to Allocate Random/Dynamic Port in Spring Boot Application?
Open your Spring Boot application and go to the application.properties file. If you want a fixed port then make the following changes in the application.properties file.
Fixed Port:
server.port=8085
But if you want a random/dynamic port then make the following changes in the application.properties file.
Random/Dynamic Port:
server.port=0
You can also set a random port in a custom predefined range by making the following changes in the application.properties file.
Random port in a custom predefined range:
server.port=${random.int(8080,9090)}
Let's understand the whole concept by developing a working Spring Boot application.
Example Spring Boot Project
Step 1: Create a New Spring Boot Project in Spring Initializr
To create a new Spring Boot project, please refer to How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA. For this project choose the following things
- Project: Maven
- Language: Java
- Packaging: Jar
- Java: 17
Please choose the following dependencies while creating the project.
- Spring Boot DevTools
- Spring Data JPA
- MySQL Driver
- Spring Web
Generate the project and run it in IntelliJ IDEA by referring to the above article.
Note: We have used the MySQL database in this project.
Step 2: Create Schema in MySQL Workbench and Put Some Sample Data
Go to your MySQL Workbench and create a schema named gfgmicroservicesdemo and inside that create a table called employee and address and put some sample data as shown in the below image.
Employee Table:
Here we have created 4 columns and put some sample data.
- id
- name
- email
- age
Address Table:
Here we have created 4 columns and put some sample data.
- id
- city
- state
- employee_id
Note: In the Address table, employee_id is a foreign key so create it accordingly. We are going to perform a SQL join operation in our native SQL query. So create tables carefully.
Before moving to IntelliJ IDEA let's have a look at the complete project structure for our Microservices.
Step 3: Make Changes in Your application.properties File
Now make the following changes in your application.properties file.
spring.datasource.url=jdbc:mysql://localhost:3306/gfgmicroservicesdemo
spring.datasource.username=put your username here
spring.datasource.password=put your password here
spring.application.name=address-service
server.servlet.context-path=/address-service
// Random/Dynamic Port Allocation
server.port=0
Step 4: Create Your Entity/Model Class
Go to the src > main > java > entity and create a class Address and put the below code. This is our model class.
Java
package com.gfg.addressapp.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "city")
private String city;
@Column(name = "state")
private String state;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Step 5: Create Your Repository Interface
Go to the src > main > java > repository and create an interface AddressRepo and put the below code. This is our repository where we write code for all the database-related stuff.
Java
package com.gfg.addressapp.repository;
import com.gfg.addressapp.entity.Address;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@Repository
public interface AddressRepo extends JpaRepository<Address, Integer> {
@Query(
nativeQuery = true,
value
= "SELECT ea.id, ea.city, ea.state FROM gfgmicroservicesdemo.address ea join gfgmicroservicesdemo.employee e on e.id = ea.employee_id where ea.employee_id=:employeeId")
Optional<Address> findAddressByEmployeeId(@Param("employeeId") int employeeId);
}
Note: Please refer to this article to know more about JpaRepository.
Step 6: Create an AddressResponse Class
Go to the src > main > java > response and create a class AddressResponse and put the below code.
Java
package com.gfg.addressapp.response;
public class AddressResponse {
private int id;
private String city;
private String state;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Step 7: Create Your Service Class
Go to the src > main > java > service and create a class AddressService and put the below code. This is our service class where we write our business logic.
Java
package com.gfg.addressapp.service;
import com.gfg.addressapp.entity.Address;
import com.gfg.addressapp.repository.AddressRepo;
import com.gfg.addressapp.response.AddressResponse;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class AddressService {
@Autowired
private AddressRepo addressRepo;
@Autowired
private ModelMapper mapper;
public AddressResponse findAddressByEmployeeId(int employeeId) {
Optional<Address> addressByEmployeeId = addressRepo.findAddressByEmployeeId(employeeId);
AddressResponse addressResponse = mapper.map(addressByEmployeeId, AddressResponse.class);
return addressResponse;
}
}
Step 8: Create an Address Controller
Go to the src > main > java > controller and create a class AddressController and put the below code. Here we are going to create an endpoint "/address/{employeeId}" to find the address using employee_id. Thats why we have created a foreign key in the Address table and we have performed the SQL join operation in the native query to get our desired result.
Java
package com.gfg.addressapp.controller;
import com.gfg.addressapp.response.AddressResponse;
import com.gfg.addressapp.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AddressController {
@Autowired
private AddressService addressService;
@GetMapping("/address/{employeeId}")
public ResponseEntity<AddressResponse> getAddressByEmployeeId(@PathVariable("employeeId") int employeeId) {
AddressResponse addressResponse = addressService.findAddressByEmployeeId(employeeId);
return ResponseEntity.status(HttpStatus.OK).body(addressResponse);
}
}
Step 9: Create a Configuration Class
Go to the src > main > java > configuration and create a class AddressConfig and put the below code.
Java
package com.gfg.addressapp.configuration;
import com.gfg.addressapp.service.AddressService;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AddressConfig {
@Bean
public ModelMapper modelMapperBean() {
return new ModelMapper();
}
}
Note: You may refer to these two articles
Before running the Microservice below is the complete pom.xml file. Please cross-verify if you have missed some dependencies
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg.addressapp</groupId>
<artifactId>address-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>address-service</name>
<description>Address Service</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 10: Run Your Address Microservice
To run your Address Microservice src > main > java > AddressServiceApplication and click on the Run button. If everything goes well then you may see the following screen in your console. Please refer to the below image.
Now you can see in the green box a random port number (58801) has been assigned to this service. Now let's try the custom predefined range. Make the following changes in the application.properties file.
server.port=${random.int(8080,9090)}
Run your service again. Please refer to the below image.
Now you can see the port number is 8306 which is in the range between 8080-9090.
Step 11: Test Your Endpoint in Postman
Now open Postman and hit the following URL
GET: http://localhost:8306/address-service/address/2
And you can see the following response
{
"id": 1,
"city": "BLS",
"state": "Odisha"
}
Similar Reads
Spring Boot - Application Properties
Spring Boot is built on top of the Spring Framework and includes all its features while simplifying configuration and setup. It has become a favorite among developers because it provides a rapid, production-ready environment that allows them to focus on business logic instead of dealing with complex
3 min read
How to Run Spring Boot Application?
Spring Boot is built on the top of Spring and contains all the features of Spring. And it is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and set
8 min read
Containerizing Spring Boot Application
Java applications, known for their robustness sometimes become difficult to deploy and manage. This is where containerization comes into the picture. Packaging your Java app into a lightweight and self-contained independent unit can provide many benefits to the developers: PortabilityScalabilityFast
3 min read
Changing Spring Boot Properties at Runtime
Spring Boot provides a flexible way to configure application properties, typically defined statically in the application.properties or application.yml files. However, there are scenarios where properties need to be changed dynamically at runtime without restarting the application. In this article, w
5 min read
Dockerize Spring Boot Application With PostgresSQL
In recent years, Docker has revolutionized the way in which we deploy and manage applications, offering a lightweight and productive solution for packaging software and its conditions into containers. For developers working with Spring Boot, a well known Java system for building undertaking grade ap
8 min read
Spring Boot â Managing Application Properties with Profiles
In Spring Boot, managing application properties is crucial for configuring the application based on different environments (e.g., development, testing, production). Spring Boot provides a feature called Profiles to help with this. Profiles allow you to define different sets of properties for various
6 min read
How to Create a Simple Spring Boot Application?
Spring Boot is one of the most popular frameworks for building Java-based web applications. It is used because it simplifies the development process by providing default configurations and also reduces boilerplate code. In this article, we will cover the steps to create a simple Spring Boot applicat
2 min read
Dockerize Spring Boot Application with MySQL
Spring boot is the most modern framework used for building microservice-based applications today. Deploying spring boot applications requires multiple steps which require complex infrastructure and tools. Docker helps with the easy deployment of spring boot applications with the help of containers.
4 min read
Spring Boot - @LoadBalanced Annotation with Example
The @LoadBalanced annotation creates an instance of created RestTemplate load-balanced. There is no code you need to write to make the RestTemplate load-balance HTTP request it sends to an internal microservice. The RestTemplate bean will be intercepted and auto-configured by Spring Cloud. In brief,
11 min read
How to Deploy Spring Boot Application in Kubernetes ?
The Spring Boot framework provides an assortment of pre-configured templates and tools to make the development of Java-based applications simpler. With little configuration, it enables developers to quickly design production-ready, stand-alone apps. Kubernetes, commonly referred to as K8s, is an ope
7 min read