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