如何配置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

其他回答

如果你正在使用spring命令行接口(CLI),使用——将命令与spring命令参数分开,来更改端口:

春天跑你好。Groovy -- --server.port=9000

spring-boot cli

这招对我很管用:

增加了一个自定义容器类:

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
       configurableEmbeddedServletContainer.setPort(8888);
    }

}

但这仍然没有使用端口8888。

然后我设置“scanBasePackages”属性就像这样在“@SpringBootApplication”类上我的主要方法:(scanBasePackages ={"自定义容器包"})

@SpringBootApplication(scanBasePackages = {"com.javabrains.util"})
public class CourseApiApp {

    public static void main (String args []) {
        SpringApplication.run(CourseApiApp.class, args);
    }
}

它开始拾取自定义容器中的端口集。

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

server.port = 8090

服务器。对于随机端口,Port = 0

服务器。端口= 8080为自定义8080端口

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

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

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