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


当前回答

在Config文件或应用程序属性中配置端口详细信息。

e.g.

port =8876

其他回答

在Spring引导应用程序中,有两种主要方法可以更改嵌入式Tomcat中的端口。

修改application.properties

首先,您可以尝试应用程序。属性文件在/resources文件夹:

server.port = 8090

修改虚拟机选项

第二种方法,如果你想避免修改任何文件和检入你只需要在你的本地文件,你可以使用vm arg:

执行—>编辑配置—>虚拟机选项

-Dserver.port=8090

此外,如果您需要更多信息,可以查看下面的博客文章:在Spring引导应用程序上更改端口

使用属性服务器。例如,端口=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);
    }

}

根据所使用的应用程序配置文件,有三种方法可以做到这一点

a)如果您正在使用应用程序。属性文件集

server.port = 8090

b)如果您正在使用应用程序。yml文件设置YAML格式的服务器端口属性,如下所示

server:
     port: 8090

c)也可以在main方法中将属性设置为System属性

System.setProperty("server.port","8090");

延伸其他答案:

文档中有一个测试部分解释了如何在集成测试中配置端口:

41.3测试Spring Boot应用程序 41.3.3使用随机端口


在集成测试中,端口配置是使用注释@SpringBootTest和webEnvironment值完成的。


随机端口:

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

您可以使用与@Value("${local.server.port}")相同的@LocalServerPort注入值。

例子:

随机端口测试配置:

@RunWith(SpringRunner.class
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ExampleTest {
   ...
   @LocalServerPort //to inject port value
   int port;
}

定义端口:

@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)

它从服务器获取值。端口,如果已定义。

如果使用@TestPropertySource(properties = "server.port=9192")定义,它将覆盖其他定义的值。 如果不是,则从src/test/resources/application获取值。属性(如果存在)。 最后,如果没有定义它,则从默认的8080开始。

例子:

定义端口测试配置:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = "server.port=9192")
public class DemoApplicationTests {

    @Test
    public void contextLoads() {
    }

}