Spring Boot-如何获取运行端口 [英] Spring Boot - How to get the running port

查看:654
本文介绍了Spring Boot-如何获取运行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a spring boot application (using embedded tomcat 7), and I've set server.port = 0 in my application.properties so I can have a random port. After the server is booted up and running on a port, I need to be able to get the port that that was chosen.

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

I cannot use @Value("$server.port") because it's zero. This is a seemingly simple piece of information, so why can't I access it from my java code? How can I access it?

推荐答案

感谢@Dirk Lachowski向我指出了正确的方向.该解决方案并不像我想要的那样优雅,但是我可以使用它.阅读spring文档,我可以侦听EmbeddedServletContainerInitializedEvent并在服务器启动并运行后获取端口.看起来是这样-

Thanks to @Dirk Lachowski for pointing me in the right direction. The solution isn't as elegant as I would have liked, but I got it working. Reading the spring docs, I can listen on the EmbeddedServletContainerInitializedEvent and get the port once the server is up and running. Here's what it looks like -

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();
      }
    }

这篇关于Spring Boot-如何获取运行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆