Spring Boot - 如何获取正在运行的端口 [英] Spring Boot - How to get the running port
问题描述
我有一个 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屋!