Search code examples
dropwizard

How to get application port programmatically in Dropwizard


I am using dropwizard version 0.7.1. It is configured to use "random" (ephemeral?) port (server.applicationConnectors.port=0). I want to get what port is really in use after startup, but I can't find any information how to do that.


Solution

  • You can get a serverStarted callback from a lifecycle listener to figure this out.

    @Override
    public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
      environment.lifecycle().addServerLifecycleListener(new ServerLifecycleListener() {
        @Override
        public void serverStarted(Server server) {
          for (Connector connector : server.getConnectors()) {
            if (connector instanceof ServerConnector) {
              ServerConnector serverConnector = (ServerConnector) connector;
              System.out.println(serverConnector.getName() + " " + serverConnector.getLocalPort());
              // Do something useful with serverConnector.getLocalPort()
            }
          }
        }
      });
    }