java 关闭 Spring ApplicationContext
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17270066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closing a Spring ApplicationContext
提问by Scorpio
When I create a new Spring ApplicationContext, for example via
当我创建一个新的 Spring ApplicationContext 时,例如通过
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).
Eclipse (STS 3.2.0) 会将其标记为潜在的资源泄漏,并抱怨它从未关闭('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?
到现在为止还挺好。然后我试图调查这个问题,但无法找到一个close()
或shutdown()
或类似的方法,甚至可以让我关闭ApplicationContext
. 这是 Eclipse 警告失控、预期设计还是我遗漏了什么?
回答by zagyi
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.
您声明ac
as ApplicationContext
which 没有定义close()
方法。而不是使用任何AnnotationConfigApplicationContext
扩展的超类型Closeable
(例如ConfigurableApplicationContext
)提供close()
释放所有资源所需的方法。
回答by mkdev
If you use Java 7 you can use the try-with-resources statement to do the work for you
如果您使用 Java 7,您可以使用 try-with-resources 语句为您完成工作
try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(...))
{
...
}
回答by Slava Semushin
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()
.
是的,接口ApplicationContext
没有close()
方法,但子类AbstractApplicationContext
,并GenericApplicationContext
有close()
和destroy()
。所以,我建议改用它们。还有有用的方法registerShutdownHook()
。
回答by Shimon Doodkin
Downcast your ApplicationContext to ConfigurableApplicationContext which defines close() method:
将您的 ApplicationContext 向下转换为 ConfigurableApplicationContext ,它定义了 close() 方法:
((ConfigurableApplicationContext)appCtx).close();
((ConfigurableApplicationContext)appCtx).close();