# 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}")`的元数据，在常规的应用中不要尝试注入端口。正如我们看到的，该值只会在容器初始化后设置。相对于测试，应用代码回调处理的会更早（例如在该值实际可用之前）。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/ix.-how-to-guides/75.-embedded-web-servers/75.6-discover-the-http-port-at-runtime.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
