Java : How to change default port in Spring Boot ?

Motivation

We wants to change the default port of the spring boot so here we will learn all the possible way to change the port number

NOTE

usually we will use the first two approaches only :)

  1. Property Files
  2. Spring Profiles
  3. Command Line
  4. Using main class

Property Files

Default port for spring boot is 8080 we can modify this port using the application.properties files which is stored in src/main/resources.

server.port=8081

Spring profiles

There is a case like when we wanted to run different ports on different machines based on the environments

Ex. in Dev we wants to use 9090 and in prod we wants to use 1080 in this case we can create the spring profiles --> application-dev.properties and application-prod.properties, inside that we can directly change the port number

server.port=9090

Command Line

While creating the jar file we can set the port number to any value and this will be serverd as a argument.

java -jar spring-5.jar --server.port=8083

Using Main class

@SpringBootApplication
public class CustomApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CustomApplication.class);
        app.setDefaultProperties(Collections
          .singletonMap("server.port", "8083"));
        app.run(args);
    }
}