...

How to configure port for a Spring Boot application?

Configuring the port for a Spring Boot application can be done using various methods. The most common approach is to set the port in the application.properties or application.yml file. Here are the steps:

Method 1: Using application.properties or application.yml

Open the src/main/resources/application.properties or src/main/resources/application.yml file and add the following line:

server.port=8080

Replace “8080” with the port number of your choice.

Method 2: Using application.properties with a Different Name

If you prefer using a different name for your configuration file (e.g., application-dev.properties), you can specify it during application startup:

java -jar your-application.jar --spring.config.name=application-dev

Method 3: Command Line Argument

You can also specify the port directly as a command-line argument when starting the application:

java -jar your-application.jar --server.port=8080

Method 4: Programmatically in Java Code

If you want to configure the port programmatically in your Java code, you can create a class that implements WebServerFactoryCustomizer<ConfigurableWebServerFactory>:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;

@SpringBootApplication
public class YourApplication implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        factory.setPort(8080); // Replace with the port of your choice
    }
}

Method 5: Using Environment Variable

You can set the port using an environment variable. For example:

export SERVER_PORT=8080
java -jar your-application.jar

Choose the method that best fits your needs and preferences. In most cases, configuring the port in the application.properties or using a command-line argument is straightforward and commonly used.

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.