Spring ApplicationContext - 资源泄漏:'context'从不关闭 [英] Spring ApplicationContext - Resource leak: 'context' is never closed

查看:562
本文介绍了Spring ApplicationContext - 资源泄漏:'context'从不关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ApplicationContext上下文中的一个变量= 
new ClassPathXmlApplicationContext(META-INF / userLibrary.xml);
service = context.getBean(UserLibrary.class);

UserLibrary是我在我的应用程序中使用的第三方实用程序。上面的代码为'context'变量生成一个警告。该警告如下所示:

 资源泄漏:'context'从不关闭

我不明白警告。由于应用程序是Spring MVC应用程序,因此在应用程序运行时,我无法真正关闭/销毁上下文。

解决方案

由于应用程序上下文是一个 ResourceLoader (即I / O操作),它会消耗某些需要释放的资源。它也是 AbstractApplicationContext 的扩展,它实现 Closable 。因此,它有一个 close()方法,可以在 try-with-resources语句

  try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(META-INF / userLibrary.xml)){
service = context.getBean(UserLibrary.class);
}

无论您是否真的需要创建此上下文是一个不同的问题(您链接到它不会对此发表评论。



当应用程序停止时,上下文是隐式关闭的,但这还不够好。 Eclipse是对的,您需要采取措施手动关闭其他情况,以避免类加载程序泄漏。


In a spring MVC application, I initialize a variable in one of the service classes using the following approach:

ApplicationContext context = 
         new ClassPathXmlApplicationContext("META-INF/userLibrary.xml");
service = context.getBean(UserLibrary.class);

The UserLibrary is a 3rd party utility which I am using in my application. The above code generates a warning for the 'context' variable. The warning is shown below:

Resource leak: 'context' is never closed

I don't understand the warning. As the application is a Spring MVC application, I can't really close/destroy the context as I refer to the service while the application is running. What exactly is the warning trying to tell me?

解决方案

Since the app context is a ResourceLoader (i.e. I/O operations) it consumes resources that need to be freed at some point. It is also an extension of AbstractApplicationContext which implements Closable. Thus, it's got a close() method and can be used in a try-with-resources statement.

try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/userLibrary.xml")) {
  service = context.getBean(UserLibrary.class);
}

Whether you actually need to create this context is a different question (you linked to it), I'm not gonna comment on that.

It's true that the context is closed implicitly when the application is stopped but that's not good enough. Eclipse is right, you need to take measures to close it manually for other cases in order to avoid classloader leaks.

这篇关于Spring ApplicationContext - 资源泄漏:'context'从不关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆