I am trying to programmatically restart my Spring Application without having the user to intervene.
Basically, I have a page which allows to switch the mode of the a
As was commented already, the restart-via-thread implementations given before only work once, and second time around throw a NPE because context is null.
This NPE can be avoided by having the restart thread use the same class loader as the initial main-invoking thread:
private static volatile ConfigurableApplicationContext context;
private static ClassLoader mainThreadClassLoader;
public static void main(String[] args) {
mainThreadClassLoader = Thread.currentThread().getContextClassLoader();
context = SpringApplication.run(Application.class, args);
}
public static void restart() {
ApplicationArguments args = context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(Application.class, args.getSourceArgs());
});
thread.setContextClassLoader(mainThreadClassLoader);
thread.setDaemon(false);
thread.start();
}