Spring Boot 端口设置

目录
  1. 指定端口
  2. 随机端口
  3. 获取端口号

本文介绍了Spring Boot设置Http端口的几种方式
Spring Boot默认端口为8080

指定端口

在Spring Boot配置文件application.propertites中设置server.port

1
server.port=8888

添加VM配置 -Dserver.port=8888 亦可指定配置

随机端口

1
server.port=0

获取端口号

使用@LocalServerPort注解可在运行时获取程序的Http端口号

1
2
3
4
5
6
7
8
9
10
11
12
13
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class MyWebIntegrationTests {

@Autowired
EmbeddedWebApplicationContext server;

@LocalServerPort
int port;

// ...

}

官方文档详见