Although Alex’s solution works, I don’t believe in including two additional dependencies ( Actuator and Cloud Context ) in order to be able to perform one operation. Instead, I combined his answer and changed my code to do what I wanted.
So, first of all, it is important that the code is executed using new Thread() and setDaemon(false); . I have the following endpoint method that handles a restart:
val restartThread = Thread { logger.info("Restarting...") Thread.sleep(1000) SpringMain.restartToMode(AppMode.valueOf(change.newMode.toUpperCase())) logger.info("Restarting... Done.") } restartThread.isDaemon = false restartThread.start()
Thread.sleep(1000) not required, but I want my controller to display a view before actually restarting the application.
SpringMain.restartToMode has the following:
@Synchronized fun restartToMode(mode: AppMode) { requireNotNull(context) requireNotNull(application)
Where context and application come from the main method when starting the application:
val args = ArrayList<String>() lateinit var context: ConfigurableApplicationContext lateinit var application: SpringApplication @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { this.args += args val builder = SpringApplicationBuilder(SpringMain::class.java) application = builder.application() context = builder.build().run(*args) }
I'm not quite sure if this is creating problems. If so, I will update this answer. Hope this helps any other.
source share