Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a Spring ApplicationContext

Tags:

java

spring

When I create a new Spring ApplicationContext, for example via

final ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfiguration.class);

Eclipse (STS 3.2.0) will mark it as a potential resource leak, complaining it is never closed ('Resource leak: 'ac' is never closed).

So far, so good. Then I tried to look into the issue, and was not able to find a close() or shutdown() or similar method that would even allow me to close the ApplicationContext. Is this an Eclipse warning go haywire, intended design or am I missing something?

like image 744
Scorpio Avatar asked Jun 24 '13 07:06

Scorpio


People also ask

What is the preferred way to close an application context?

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.

Why do we need to close application context?

It is important to close the context properly because different lifecycle methods must have the chance to run. Consequently, the application can release the resources and do some clean-up.

How do you gracefully shutdown a Spring boot application?

In the Spring Boot Document, they said that 'Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. ' When I click ctrl+c on the shell command, the application can be shutdown gracefully.


2 Answers

You declare ac as ApplicationContext which doesn't define a close() method. Instead of that use any super-type of AnnotationConfigApplicationContext that extends Closeable (e.g. ConfigurableApplicationContext) providing the close() method you need to release all resources.

like image 56
zagyi Avatar answered Sep 23 '22 22:09

zagyi


If you use Java 7 you can use the try-with-resources statement to do the work for you

try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(...))
{
  ...
}
like image 31
mkdev Avatar answered Sep 23 '22 22:09

mkdev