0

Is it possible to close the context from an ApplicationListener?

 public class MyListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { // on some certain condition we want to shutdown spring ie close the context ((ConfigurableApplicationContext)event.getApplicationContext()).close(); } } 

The problem is that Spring still wants to finish the startup process here:

public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } 

And therefore throws an IllegalStateException:

java.lang.IllegalStateException: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@dcb84c98 has been closed already

2 Answers 2

3

It seems likely that the question you actually wanted to ask is "How do I interrupt Spring-Boot startup".

Throw an exception from your onApplicationEvent method.

Sign up to request clarification or add additional context in comments.

Comments

0

Its seems that you want to interrupt Spring on startup.

Simple you will not able to do that with out getting error.

If you will still like to kill your application while startup just use:

System.exit(0); 

But if you want to close the context after the initial you can listen to a different Spring event called ApplicationReadyEvent

@Component public class MyListener { @EventListener public void onApplicationEvent(ApplicationReadyEvent event) throws Exception { event.getApplicationContext().close(); } } 

ApplicationReadyEvent - Event published as late as conceivably possible to indicate that the application is * ready to service requests

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.