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


当前回答

如文档中所说,要么设置服务器。端口作为系统属性使用命令行选项jvm -Dserver。端口=8090或添加应用程序。/src/main/resources/ with中的属性

server.port=8090

随机使用端口:

server.port=0

类似地,添加应用程序。Yml /src/main/resources/

server:
  port: 8090

其他回答

如文档中所说,要么设置服务器。端口作为系统属性使用命令行选项jvm -Dserver。端口=8090或添加应用程序。/src/main/resources/ with中的属性

server.port=8090

随机使用端口:

server.port=0

类似地,添加应用程序。Yml /src/main/resources/

server:
  port: 8090

“服务器。Port =8080"将只工作,如果你运行应用程序作为一个jar通过main方法,

如果您通过tomcat容器将此应用程序作为war文件运行,则此配置将不起作用。

如果你在使用应用程序。yml添加以下行到它

server:
     port: 9000

当然,随机端口是0。

通过编程方式,使用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);
    }

}

由于Spring Boot提供了各种配置外部化机制(通过各种PropertySource实现和/或按顺序连接到Environment对象的处理器),您可以通过以下方法设置jar存档之外的任何属性:

Pass property through command line argument as application argument java -jar <path/to/my/jar> --server.port=7788 From property in SPRING_APPLICATION_JSON (Spring Boot 1.3.0+) Define environment variable in U*IX shell: SPRING_APPLICATION_JSON='{"server.port":7788}' java -jar <path/to/my/jar> By using Java system property: java -Dspring.application.json='{"server.port":7788}' -jar <path/to/my/jar> Pass through command line argument: java -jar <path/to/my/jar> --spring.application.json='{"server.port":7788}' Define JVM system property java -Dserver.port=7788 -jar <path/to/my/jar> Define OS environment variable U*IX Shell SERVER_PORT=7788 java -jar <path/to/my/jar> Windows SET SERVER_PORT=7788 java -jar <path/to/my/jar> Place property in ./config/application.properties configuration file server.port=7788 and run: java -jar <path/to/my/jar> Place property in ./config/application.yaml server: port: 7788 and run: java -jar <path/to/my/jar> Place property in ./application.properties server.port=7788 and run: java -jar <path/to/my/jar> Place property in ./application.yaml server: port: 7788 and run: java -jar <path/to/my/jar>


您可以将上述方法组合在一起,列表中的前一个配置优先于后一个配置。

例如:

SERVER_PORT=2266 java -Dserver.port=5566 -jar <path/to/my/jar> --server.port=7788

服务器将在端口7788上启动并监听。

这非常有用,在PropertySources中提供优先级较低的默认属性(通常打包在存档中或编码在源代码中),然后在运行时环境中覆盖它。这就是Spring Boot的设计理念:

坚持己见,但当需求开始偏离默认值时,要迅速离开。


SERVER_NAME到server.name的转换由放松绑定完成。