如何为Spring Boot应用程序配置端口

1059

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


12
如果有人感兴趣,这里展示了如何有多个端口-https://dev59.com/GVoV5IYBdhLWcg3wXNs9 - Betlista
如果您使用“yml”文件进行配置,则可以使用以下内容: server: port: 8081 同时,将您的主类注释为“@SpringBootApplication”,并删除“@EnableAutoConfiguration”。 - Keaz
你的项目[application.properties]中添加以下内容: server.port=8080 - Lahiru Samishka
在应用程序属性中设置server.port=8080。此配置位于org.springframework.boot.autoconfigure.web下的ServerProperties.class类中。 - Atif
64个回答

4

只需设置环境变量 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 -jarmvn 命令之前添加其他子命令,则需要添加 export 命令来单独设置环境变量,并通过 ; 分隔它们,以确保它们对子进程可用。
    例如:
    export SERVER_PORT=9093; export MAVEN_OPTS="-Xmx256m -Xms64m"; mvn spring-boot:run

4

有三种方法可以实现

1 在application.properties文件中设置server.port属性

server.port = 8090

2 在 application.yml 文件中设置服务器端口属性

server:
     port: 8090

main方法中将属性设置为系统属性。
System.setProperty("server.port","8090");

3
除了所有的答案之外,我想指出大多数IDE(IntelliJ与Spring插件、STS)都有一个功能,它会建议由SpringBoot支持的所有配置键。(即所有基于意见的配置关键字)

enter image description here

IntelliJ 的 Spring 插件


3

服务器端口声明有两种类型

1.静态类型

   server.port=8080. // your port number
  1. Dynamic type

     server.port=0.      // randomly generate port number. 
     server.port=${PORT:0}
    

为什么给定的端口号'8080.'和'0.'后面有点号? - Dirk Schumacher

2
这个问题是谷歌搜索“Gradle Spring Port”时的第一个结果。
如果你在使用Gradle,且已经应用了Spring Boot Gradle插件,可以像下面这样做:
bootRun {
    args += ["--server.port=[PORT]"]
}

如果您需要更加精细的答案,请查看我在这里的回答。


2

2

如果您正在使用引导项目并想要配置端口,则可以在application.properties文件中输入,注意:属性文件应位于src/main/resource下。

Spring属性

server.port=9999 如果您正在使用CMD,则请遵循以下命令 -Dserver.port=9999 对于默认端口,其server.port = 0 确保没有任何端口正在使用此端口号


2

使用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);
    }

}

2
在应用程序属性中,只需添加一行即可。最初的回答。
server.port = 8090

这是一个重复的答案。 - nikiforovpizza

2
默认端口是8080,但我们可以在application.properties文件中自定义端口号,如下所示:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
server.port = 5050 -- #here we can give any port number.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接