springspring-bootportembedded-tomcat-7

Spring Boot - How to get the running port


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.

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?


Solution

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