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


当前回答

你可以在java代码中设置port:

HashMap<String, Object> props = new HashMap<>();
props.put("server.port", 9999);

new SpringApplicationBuilder()
    .sources(SampleController.class)                
    .properties(props)
    .run(args);

或者在application.yml中:

server:
    port: 9999

或者在application.properties中:

server.port=9999

或者作为命令行参数:

-Dserver.port=9999

其他回答

正如大家所说,您可以在application.properties中指定 服务器。Port = 9000(可以是任何其他值) 如果您在项目中使用弹簧执行器,默认情况下它指向 8080,如果你想改变它,在应用程序中。属性提 管理。Port = 9001(可以是任何其他值)

由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

在应用中提供端口号。属性文件将解决该问题

 server.port = 8080

“端口取决于您的选择,您希望将应用程序托管在哪里”

除了所有的答案,我想指出的是,大多数IDE (IntelliJ与Spring插件,STS)都有一个功能,它建议SpringBoot支持的所有配置键。(即所有自以为是的配置关键字)

Spring插件Intellij

此外,您还可以以编程方式配置端口。

对于Spring Boot 2.x.x:

@Configuration
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
  public void customize(ConfigurableServletWebServerFactory factory){
    factory.setPort(8042);
  }
}

对于旧版本:

@Configuration
public class ServletConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            container.setPort(8012);
        });
    }
}