简体   繁体   中英

Change default Port of Spring Boot application from frontend with thymeleaf

Is it possible to change the spring boot port from the frontend (by using thymeleaf) over a Endpoint on a @Controller?

And how can i programatically restart the application with the new configured port?

As stated here , you can set the server port like this:

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component; 

@Component
public class AppCustomContainer 
  implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

  @Override
  public void customize(ConfigurableWebServerFactory factory) {
  
   factory.setPort(1234);
  
  }
}

Instead of 1234, you can use a file to store the port (when changing it) and load it when starting

After that, you can restart the application as described here :

  • Add actuator and spring-cloud:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • Enable restarting in the application.properties : management.endpoint.restart.enabled = true
  • Add an the instance of RestartEndpoint :
@Autowired
private RestartEndpoint restartEndpoint;

And run this in order to restart:

Thread restartThread = new Thread(restartEndpoint::restart);
restartThread.setDaemon(false);
restartThread.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM