Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to force Spring shutdown from a bean?

Tags:

java

spring

My application uses a Spring DefaultMessageListenerContainer to process incoming messages. The main method of the app already registers a shutdown hook.

Question is this: what is the best way to force the application context to shut down?

If I throw a RuntimeException in the message listener, it is handled by the container, and not passed on. Is calling System.exit acceptable? Do I pass along the ApplicationContext to every class that needs to shut down, so I can call close() on it?

like image 211
xcut Avatar asked Mar 08 '10 12:03

xcut


People also ask

How do you gracefully shutdown a spring boot application?

Use the static exit() method in the SpringApplication class for closing your spring boot application gracefully.

How do I turn off Spring container?

Another option to shutdown the Spring Boot application is to close Spring ApplicationContext using SpringApplication . SpringApplication. run(String…) method returns ApplicationContext as a ConfigurableApplicationContext We can use close() method to close ApplicationContext programmatically.

What is destroy method close in Spring?

destroy-method is bean attribute using which we can assign a custom bean method that will be called just before the bean is destroyed. To use the destroy-method attribute, we do as follows. Here myPreDestroy() method will be defined in the Student class. Spring will call this method just before destroying the bean.

Which of the following commands is used to shutdown a spring boot application?

Using SpringApplication#exit() method.


1 Answers

You can cast your application context to ConfigurableApplicationContext and call close() on it. At least that's what happens when the context is shut down in a web-application environment, in cases the servlet context is destroyed.

If you want to get ahold of the ApplicationContext, your bean may implement ApplicationContextAware

Another option is to inject (or autowire with @Autowired) the application context:

@Inject
private ApplicationContext ctx;
like image 73
Bozho Avatar answered Sep 23 '22 18:09

Bozho