如何配置Spring Boot应用程序侦听的TCP/IP端口,使其不使用默认端口8080。


当前回答

默认情况下,spring启动应用程序从默认端口8080启动嵌入式tomcat服务器。Spring为您提供了以下不同的自定义,您可以从中选择一种。

说明—您可以使用服务器。Port =0 spring引导将找到任何未分配的HTTP随机端口 对我们来说。

1) application.properties

server.port=2020

2) application.yml

server:  
     port : 2020

3)通过编程方式更改服务器端口

3.1)通过实现WebServerFactoryCustomizer接口- Spring 2.x

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // customize the factory here
        factory.setPort(2020);
    }
}

3.2)通过实现EmbeddedServletContainerCustomizer接口- Spring 1.x

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        // customize here
        container.setPort(2020);
    }
}

4)使用命令行选项

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

其他回答

只需设置环境变量SERVER_PORT。 (这些例子适用于Linux)

使用java -jar启动: SERVER_PORT=9093 java -jar target/eric-sc-dummy.jar 通过maven spring-boot插件启动: SERVER_PORT=9093 mvn spring-boot:run

小贴士:

如果你在java -jar或mvn命令之前添加了其他子命令,那么你需要在一个单独的命令中添加export来设置env,并通过;将它们分开,以确保它对子进程可用。 例句: 出口SERVER_PORT = 9093;export MAVEN_OPTS="-Xmx256m -Xms64m";运行mvn spring-boot:

实际上,最简单的方法是设置服务器。端口属性。

如果你使用STS作为IDE,从3.6.7版本开始,你实际上有Spring Properties Editor来打开属性文件。

该编辑器为所有Spring Boot属性提供了自动补全功能。如果你写端口并按CTRL + SPACE,服务器。端口将是第一选择。

通过编程方式,使用spring boot 2.1.5:

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory server) {
        server.setPort(9000);
    }

}

您还可以使用SERVER_PORT环境变量来配置Spring Boot端口。只需设置环境变量并重新启动应用程序:

set SERVER_PORT=9999 // on windows machine
export SERVER_PORT=9999 // on linux

请注意,如果你没有在系统范围内设置这些环境变量,你应该在同一个会话上运行引导应用程序。

你可以在应用程序中设置。/src/main/resources/下的属性

server.port = 8090