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?
You declare ac
as ApplicationContext
which doesn't define a close()
method. Instead of that use any super-type of AnnotationConfigApplicationContext
that extends Closeable
(eg 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(...))
{
...
}
Yes, interface ApplicationContext
doesn't have close()
method, but child classes AbstractApplicationContext
and GenericApplicationContext
have close()
and destroy()
. So, I suggest to use them instead. Also there is useful method registerShutdownHook()
.
Downcast your ApplicationContext to ConfigurableApplicationContext which defines close() method:
((ConfigurableApplicationContext)appCtx).close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.