How to configure port for a Spring Boot application

To configure the port for a Spring Boot application, you can use the server.port property in the application's configuration file. The configuration file can be a application.properties file in the classpath, or a application.yml file in the classpath.

For example, to configure the port for a Spring Boot application to 8080, you can add the following line to the configuration file:

server.port=8080

You can also set the port for a Spring Boot application programmatically by using the SpringApplication.setDefaultProperties method. For example:

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

This code sets the default value for the server.port property to 8080 before the application is run.

You can also set the port for a Spring Boot application by specifying the --server.port command-line argument when starting the application. For example:

java -jar myapp.jar --server.port=8080

Note that the server.port property can also be set using an environment variable or system property. The configuration file, programmatic configuration, and command-line arguments are all checked in order, with later sources taking precedence over earlier ones.