How to configure port for a Spring Boot application

前端 未结 30 1717
名媛妹妹
名媛妹妹 2020-11-22 13:36

How do I configure the TCP/IP port listened on by a Spring Boot application, so it does not use the default port of 8080.

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 14:12

    By default spring boot app start with embedded tomcat server start at default port 8080. spring provides you with following different customization you can choose one of them.

    NOTE – you can use server.port=0 spring boot will find any unassigned http random port for us.

    1) application.properties

    server.port=2020
    

    2) application.yml

    server:  
         port : 2020
    

    3) Change the server port programatically

    3.1) By implementing WebServerFactoryCustomizer interface - Spring 2.x

    @Component
    public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer {
    
        @Override
        public void customize(TomcatServletWebServerFactory factory) {
            // customize the factory here
            factory.setPort(2020);
        }
    }
    

    3.2) By Implementing EmbeddedServletContainerCustomizer interface - Spring 1.x

    @Component
    public class CustomizationBean implements EmbeddedServletContainerCustomizer {
    
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            // customize here
            container.setPort(2020);
        }
    }
    

    4) By using command line option

     java -jar spring-boot-app.jar -Dserver.port=2020
    

提交回复
热议问题