silent-box
silent-box

Reputation: 1666

Spring Boot: exit jvm on "Application run failed"

Is there a way to react on "Application run failed", e.g. in case when database is unavailable?

In my case the desired behavior is to exit the JVM process, so the docker container will be automatically restarted

I tried to listen for "ContextClosedEvent", but it does not work for the startup failure case.

Upvotes: 3

Views: 1119

Answers (1)

DanielSP
DanielSP

Reputation: 368

To anyone who need to kill application on any failure during startup (example in kotlin):

@SpringBootApplication
class MyApplication

fun main(args: Array<String>) {
    val application = SpringApplication()
    application.addListeners(FailedInitializationMonitor())
    application.addPrimarySources(listOf(MyApplication::class.java))
    application.run(*args)
}

class FailedInitializationMonitor : ApplicationListener<ApplicationFailedEvent> {

    override fun onApplicationEvent(event: ApplicationFailedEvent) {
        exitProcess(1)
    }
    
}

Upvotes: 2

Related Questions