Reputation: 946
I'm using Spring Boot and I've got a use case where user can upload a file which should cause a restart of application (since user's upload is used during creation of multiple beans). I know I can avoid restarting the application, but at the moment - this is what I want.
I've found RestartEndpoint in Spring-Cloud project, but it doesn't seem like ApplicationPreparedEvent
is fired. Is there any other way I can programmatically restart Spring Boot application?
Upvotes: 12
Views: 8233
Reputation: 324
I used the below code to restart my application from the code itself. Closing context using a separate thread will not shut the JVM.
public class DemoApplication {
private static String[] args;
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
DemoApplication.args = args;
context = SpringApplication.run(DemoApplication.class, args);
}
public static void restart() {
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(DemoApplication.class, DemoApplication.args);
});
thread.setDaemon(false);
thread.start();
}
Upvotes: 0
Reputation: 14551
I have a special case in which my Spring Boot application, which runs on Linux
, is required to run as root
.
Since I run the application as systemd
service, I can restart it like this:
Runtime.getRuntime().exec(new String[] { "/bin/systemctl", "restart", "foo" });
If your application is (hopefully) not required to run as root
, a setuid
wrapper-script could be used, or better, use sudo
.
Check this answer on how to do that:
https://superuser.com/questions/440363/can-i-make-a-script-always-execute-as-root
Upvotes: 3
Reputation: 1214
The simplest way to do this by calling the refresh()
method on the Spring ApplicationContext. This will kill and reload all of your beans, so you should be certain that this occurs only when it is safe for your application to do so.
Upvotes: 3
Reputation: 1860
In your case it might be possible to use the /refresh endpoint (see http://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_endpoints) and annotate the beans that depend on the changed configuration with @RefreshScope.
Upvotes: 1