Spring Boot - changing web server port programmatically

344 Views Asked by At

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
0

There are 0 best solutions below