Spring
May 28, 2020

M01 Q09 What is the preferred way to close an application context? Does Spring Boot do this for you?

A preferred way to close an application context depends on the type of application that you are creating.

Standalone Non-Web Applications

  • Register Shutdown hook by calling ConfigurableApplicationContext#registerShutdownHook

If you are creating standalone non-web application then the preferred and the recommended way is to register Shutdown hook by calling registerShutdownHook from theConfigurableApplicationContext.

On the screen above, I am using registerShutdownHook to close context and also it will call the @PreDestroy method of SpringBean1.class.

In the next example, I am using try with resources. Basically it will automatically close the application context. It's because the application context implements Autocloseable interface.

  • Call ConfigurableApplicationContext#close

Also, there is another way, you can call the close() method directly on the application context.

In the third example, I call the close() method directly. This way is not recommended because, for example, when you have exception above close() method, it will not get called.

Web Application

ContextLoaderListener will automatically close context when web container will stop the web application

For web applications, the context will be closed automatically. When the web container will want to stop the application, the ContextLoadListener will receive the event from the servlet. And then based on this event it will close the application context.

After the undeploy of application, the @PreDestroy method will be called and the application context will be closed.

Spring Boot

  • Application Context will be automatically closed
  • Shutdown hook will be automatically registered
  • ContextLoaderListener applies to Spring Boot Web Applications as well

For Spring Boot applications, context will be closed automatically. And this is done by registering the shutdown hook for the CLI applications.

Here I am using CommandLineRunner. And as you can see I have not registered the shutdown hook or close context manually. That is because Spring Boot automatically registered the shutdown hook.