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?
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.
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.
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.
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.
If you use Java 7 you can use the try-with-resources statement to do the work for you
try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(...))
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With