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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:32:39  来源:igfitidea点击:

Closing a Spring ApplicationContext

javaspring

提问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 acas ApplicationContextwhich doesn't define a close()method. Instead of that use any super-type of AnnotationConfigApplicationContextthat extends Closeable(e.g. ConfigurableApplicationContext) providing the close()method you need to release all resources.

您声明acas ApplicationContextwhich 没有定义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 ApplicationContextdoesn't have close()method, but child classes AbstractApplicationContextand GenericApplicationContexthave close()and destroy(). So, I suggest to use them instead. Also there is useful method registerShutdownHook().

是的,接口ApplicationContext没有close()方法,但子类AbstractApplicationContext,并GenericApplicationContextclose()destroy()。所以,我建议改用它们。还有有用的方法registerShutdownHook()

回答by Shimon Doodkin

Downcast your ApplicationContext to ConfigurableApplicationContext which defines close() method:

将您的 ApplicationContext 向下转换为 ConfigurableApplicationContext ,它定义了 close() 方法:

((ConfigurableApplicationContext)appCtx).close();

((ConfigurableApplicationContext)appCtx).close();

see https://stackoverflow.com/a/14424009/466363

https://stackoverflow.com/a/14424009/466363