Reputation: 391
I am workign on a spring boot application that from time to time crashed or has some strange connection errors. While it is a different matter if its a good solution to just restart the application in case of an error, i still want this is as a kind of last resort method. Basicly i want to understand how to restart the whole application after each iteration of a loop. I have tried Baeldungs tutorial on Programmatically Restarting a Spring Boot Application but the code is not working since in this approach:
@SpringBootApplication
public class Application {
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
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.setDaemon(false);
thread.start();
}
}
context only contains a null value and therefore throws a nullpointer exception. As you can see in the comments i am not the only one having this problem. I also tried the solution from the comment section using the org.springframework.boot.devtools.restart.Restarter class
Here you can basicly see the big loop with my main controller and that it should restart in case any unhandled exception occurs.
@Override
public void run(String... args) {
try {
while (true){
try {
mainController.run;
} catch (Exception | CacheDataException e){
log.error("Exception in Main controller");
Restarter.getInstance().restart();
} finally {
log.info("Restarting mainController.");
}
}
} finally {
log.info("Closing the application.");
this.sshSession.shutdown();
System.out.println(BananaUtils.bananansi("Tier 2 ends", Ansi.BLUE));
}
}
If i do that however i get about 1000 exceptions and errors thrown from INSIDE the mainController resulting in endless attempts to restart the application eventually crashing with Overflow errors etc.
Why is it even continuing the loop when it should just restart the application ? What is an elegant way to just simply restart the application. It would even be enough if all the beans get reset. I just want the whole thing to reset itself and start from a new.
Any ideas ?
Thanks
Upvotes: 0
Views: 1629