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


当前回答

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

server.port = 8090

其他回答

使用属性服务器。例如,端口=8080,就像在其他答案中提到的那样,绝对是一种方法。只是想提一下,你也可以暴露一个环境属性:

SERVER_PORT=8080

因为在最近的版本中,spring boot能够替换“_”中的“。”,并将环境变量的小写改为大写。 这在容器中特别有用,在容器中,你所要做的就是定义环境变量,而不需要添加/编辑应用程序。属性或通过命令行传递系统属性(即-Dserver.port=$PORT)

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

}

类似于https://stackoverflow.com/a/36865796/1587329和https://stackoverflow.com/a/40799750/1587329, gradle的一行代码是

SERVER_PORT=9090 gradle bootRun

Spring-web模块默认提供了一个运行在端口号8080上的嵌入式tomcat服务器。

您可以修改如下-

A)如果你使用gradle,那么可以在你的应用程序中设置属性。yml:

 server:  
      port: 8042

B)如果你正在使用maven,那么你可以在你的应用程序中设置属性。属性:

server.port: 8042

C)当你在自己的配置文件中有端口,并想在运行时设置它。

通过实现WebServerFactoryCustomizer接口- Spring 2.x

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // customize the factory here
        factory.setPort(8042);
    }
}

通过实现EmbeddedServletContainerCustomizer接口- Spring 1.x

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        // customize here
        container.setPort(8042);
    }
}

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

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

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