> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/ix.-how-to-guides/75.-embedded-web-servers/75.6-discover-the-http-port-at-runtime.md).

# 75.6 在运行时发现HTTP端口

你可以从输出的日志或通过它的`EmbeddedWebServer`从`ServletWebServerApplicationContext`获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener<ServletWebServerInitializedEvent>`类型的`@Bean`，然后当事件发布时将容器pull出来。

使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`进行测试时，你可以通过`@LocalServerPort`注解将实际端口注入到字段中，例如：

```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class MyWebIntegrationTests {

    @Autowired
    ServletWebServerApplicationContext server;

    @LocalServerPort
    int port;

    // ...

}
```

**注** `@LocalServerPort`是`@Value("${local.server.port}")`的元数据，在常规的应用中不要尝试注入端口。正如我们看到的，该值只会在容器初始化后设置。相对于测试，应用代码回调处理的会更早（例如在该值实际可用之前）。
