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


当前回答

如果端口号可以是随机的,则可以在应用程序中使用随机函数。属性server.port = $ {random.int (4)}

其他回答

在我的情况下添加声明

server.port=${port:8081}

覆盖默认的tomcat服务器端口。

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

}

由Gradle运行:

在默认端口(8080)运行:./gradlew bootRun 运行在提供的端口(8888):./gradlew bootRun——args='——server.port=8888' 如果应用中有变量。PORT=8888 ./gradlew bootRun . properties文件

由Maven运行:

Run in default port(8080): mvnw spring-boot:run Run in provided port(8888): mvnw spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085' Run in provided port(8888): mvn spring-boot:run -Dspring-boot.run.arguments='--server.port=8085' Run in provided port(8888) with other custom property: mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8899 --your.custom.property=custom" If we have any variable in the application.properties file named PORT, run this: SERVER_PORT=9093 mvn spring-boot:run

使用java -jar:

Create the .jar file: For Gradle: ./gradlew clean build. We will find the jar file inside: build/libs/ folder. For Maven: mvn clean install. We will find the jar file inside:target folder. Run in default port(8080): java -jar myApplication. jar Run in provided port(8888): java -jar myApplication.jar --port=8888 Run in provided port(8888): java -jar -Dserver.port=8888 myApplication.jar Run in provided port(8888) having variable SERVER_PORT in application.properties file: SERVER_PORT=8888 java -jar target/myApplication.jar

这个问题是Gradle Spring Port的第一个结果。

如果你使用gradle,你可以这样做,如果你有Spring Boot gradle插件已经应用:

bootRun {
    args += ["--server.port=[PORT]"]
}

想知道更复杂的答案,请看我的回答。

默认情况下,spring-web模块提供了一个嵌入式tomcat服务器,该服务器在端口号8080下运行。如果需要修改应用程序的端口号,请进入应用程序。属性文件,并使用server配置端口号。端口属性。

  server.port= 9876

然后,您的应用程序在端口9876下运行。