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