2

I am new to Springboot, just watch a tutorial saying that if I would like to change port, I must do it in the application.properties. I wonder if there is any ways to change the port. Thanks in advance

tcf01
  • 1,699
  • 1
  • 9
  • 24

1 Answers1

3

Programmatic Configuration We can configure the port programmatically by either setting the specific property when starting the application or by customizing the embedded server configuration.

First, let's see how to set the property in the main @SpringBootApplication 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);
    }
}

Next, to customize the server configuration, we have to implement the WebServerFactoryCustomizer interface:

@Component
public class ServerPortCustomizer 
  implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        factory.setPort(8086);
    }
}

Note that this applies to Spring Boot 2.x version.

For Spring Boot 1.x, we can similarly implement the EmbeddedServletContainerCustomizer interface.

Using Command Line Arguments When packaging and running our application as a jar, we can set the server.port argument with the java command:

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

Or by using the equivalent syntax:

  • java -jar -Dserver.port=8083 spring-5.jar

Learn More at: https://www.baeldung.com/spring-boot-change-port

Note: If you have mentioned 8080 in application.properties but you want to run it on 8083 then it will work by giving the port number in command line arguments as like below,

  • java -jar -Dserver.port=8083 spring-5.jar
Roshini
  • 85
  • 1
  • 8
Nivin John
  • 173
  • 1
  • 11
  • So there are only two ways. We can either set the port in the application.properties or set it in the entry function of the Spring application? – tcf01 Dec 23 '19 at 14:03
  • 2
    there are four ways as listed in the following article: https://www.baeldung.com/spring-boot-change-port – Nivin John Dec 24 '19 at 05:19
  • I don't think that just copying the answer from a site is what it is needed on Stackoverflow. You could provide just a link on the comments or at least explain it with your own words. – Nick Pantelidis Jun 02 '22 at 11:12