0

I'm building a desktop application using Spring Boot, which also uses the embedded web server to serve some generated files. Is there a way I can programmatically change the port the web server runs on? I'm going to allow the user to configure the port they want it to run on, and I'm hoping I can make the change without making them restart the desktop portion of the application.

I tried this very naïve code:


    private ServletWebServerApplicationContext webServerAppCtxt;
    private ServerProperties webServerConfig;

    @Override
    public void applyChanges() {
        webServerAppCtxt.getWebServer().stop();
        webServerConfig.setPort(Integer.parseInt(port.getText().trim()));
        webServerAppCtxt.getWebServer().start();
    }

But it didn't work. Logs just said:

Stopping service [Tomcat]
Tomcat started on port(s): -1 (http) with context path ''

Using Java 11 / Spring Boot 2.5.2

Some promising clues I haven't pieced together yet:

  • org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#createWebServer
  • org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration.EmbeddedTomcat#tomcatServletWebServerFactory
  • org.springframework.boot.web.servlet.support.SpringBootServletInitializer#createRootApplicationContext
Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • you mean like this: @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) but in our "main" code? – Book Of Zeus Jul 19 '21 at 04:29
  • @BookOfZeus I guess it'd probably be fairly similar under the hood? I just want to restart the web server just like when it normally starts at boot, but triggered by my code. – Brad Mace Jul 19 '21 at 04:38
  • you can't use application.properties? and use environment variables ? and start with java -jar ... -DPORT=13245 ...? – Book Of Zeus Jul 19 '21 at 04:42
  • @BookOfZeus I can if I have to, but I'm trying to see if there's a way to keep the Swing GUI portion of the application running and only restart the embedded web server – Brad Mace Jul 19 '21 at 04:49

0 Answers0