Get the Random Port Number in Spring Boot

In this tutorial, you will learn how to get the port number on which your Spring Boot application is running. Whether it is a defined port number or a random port number. Let’s start learning how to get the running port number first.

@LocalServerPort Annotation

If your Spring Boot application is configured to start on a random port number, then there is still a way to learn that port number.

To get the port number on which your Spring Boot application is running, you can use the @LocalServerPort annotation.

@LocalServerPort
private int localServerPort;

The @LocalServerPort annotation will pick up an actual port number on which your server is running. It will assign this port number to a locaServerPort member variable.

Alternatively, you can read the value of the local server port using the @Value annotation.

@Value("${local.server.port}")
private int localServerPort;

Defined Server Port

In some situations, you might also need to read the value of server.port property that is defined in the application.properties file. To do that, you can use the @Value annotation.

@Value("${server.port}")
private int serverPort;

Difference Between @LocalServerPort and server.port

The main difference between the value returned by @LocalServerPort and the value defined by server.port property is that @LocalServerPort annotation returns a value of a port number that is actually being used by your server. For example, when the Spring Boot application is configured to start on a random port number, the server.port property is set to zero.

server.port=0

But the actual running port number will be different.

Spring Boot Video Tutorials

I hope this tutorial was helpful to you. If you also like learning Spring Boot by watching video tutorials, I have many Spring Boot tutorials that also include video tutorials.

For video lessons on how to secure your Spring Boot application with OAuth 2.0. and Spring Security 5, please checkout my complete video course OAuth 2.0. in Spring Boot applications.

Happy learning!