diff --git a/IX. ‘How-to’ guides/64.4. Discover the HTTP port at runtime.md b/IX. ‘How-to’ guides/64.4. Discover the HTTP port at runtime.md index e69de29..8d12264 100644 --- a/IX. ‘How-to’ guides/64.4. Discover the HTTP port at runtime.md +++ b/IX. ‘How-to’ guides/64.4. Discover the HTTP port at runtime.md @@ -0,0 +1,21 @@ +### 64.4. 发现运行时的HTTP端口 + +你可以通过日志输出或它的EmbeddedServletContainer的EmbeddedWebApplicationContext获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener`类型的`@Bean`,然后当事件发布时将容器pull出来。 + +使用`@WebIntegrationTests`的一个有用实践是设置`server.port=0`,然后使用`@Value`注入实际的('local')端口。例如: +```java +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) +@WebIntegrationTest("server.port:0") +public class CityRepositoryIntegrationTests { + + @Autowired + EmbeddedWebApplicationContext server; + + @Value("${local.server.port}") + int port; + + // ... + +} +```