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


当前回答

把这段代码放在uapplicatop中。属性文件

其他回答

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

e.g.

port =8876

延伸其他答案:

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

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() {
    }

}

在应用程序属性中添加一行

server.port = 8090

在application.properties中包含下面的属性

server.port=8080

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

Spring插件Intellij