egbokul
egbokul

Reputation: 3974

How do I terminate a Spring application during startup?

I have a Spring Boot application which has some external dependencies (eg. files outside the project that need to exists in order for the application to start up properly).

One of my beans has a @PostConstruct method that does the initialization. I would like to exit cleanly and gracefully if the initialization is not successful - for example, the files are not found.

Calling ((ConfigurableApplicationContext)applicationContext).close(); in the @PostConstruct method results in

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context

and a chain of other Exceptions. Is there a way to do this properly?

Upvotes: 8

Views: 2643

Answers (2)

Lho Ben
Lho Ben

Reputation: 2149

You can use Sytem exit static method, it terminates the currently running Java Virtual Machine. the code passed indicate the termination status. by convention, a nonzero status code indicates abnormal termination.

exp:

System.exit(0);

Upvotes: -2

Clover
Clover

Reputation: 51

you can't use System.exit(0) in @PostConstruct, shutdown will waiting lock of startupShutdownMonitor, can't exit.

Upvotes: 4

Related Questions