小编典典

Spring Boot-如何获取运行端口

spring

我有一个spring boot应用程序(使用嵌入式tomcat 7),并且已经设置好了server.port = 0application.properties所以我可以有一个随机端口。服务器启动并在端口上运行后,我需要能够获取所选择的端口。

我不能使用,@Value("$server.port")因为它是零。这是一条看似简单的信息,所以为什么不能从我的Java代码访问它呢?我该如何访问?


阅读 2131

收藏
2020-04-12

共2个答案

小编典典

该解决方案并不像我想要的那样优雅,但是我可以使用它。阅读spring文档,我可以侦听EmbeddedServletContainerInitializedEvent并在服务器启动并运行后获取端口。这是它的样子

import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;




    @Component
    public class MyListener implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {

      @Override
      public void onApplicationEvent(final EmbeddedServletContainerInitializedEvent event) {
          int thePort = event.getEmbeddedServletContainer().getPort();
      }
    }
2020-04-12
小编典典

是否也可以通过类似的方式访问管理端口,例如:

  @SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
  public class MyTest {

    @LocalServerPort
    int randomServerPort;

    @LocalManagementPort
    int randomManagementPort;
2020-04-12