我在 Eclipse 中创建了一个小 bean 类。它在 NetBeans 中工作,但在 Eclipse 中它说
Resource leak: 'appContext' is never closed.
我像这样关闭了它 appContext.close();
但它不起作用。
//绘图应用程序类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class drawingapplication {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle =(Triangle) appContext.getBean("triangle");
triangle.draw();
}
}
//三角形类
package org.spring.javabeans;
public class Triangle {
public void draw(){
System.out.println("triangle drawan");
}
}
//spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN""http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="triangle" class="org.spring.javabeans.Triangle"/>
</beans>
最佳答案
ClassPathXmlApplicationContext
是 ConfigurableApplicationContext
的子类,这意味着它实现了 Closable
。
ApplicationContext
不扩展 Closeable
,因此无法在 ApplicationContext
类型的任何引用上调用 Closable#close()
方法。
但是,Eclipse 检测到您正在分配 ClassPathXmlApplicationContext
类型的值(需要关闭),并警告您应该关闭它,即使您无法通过要分配该值的变量的引用类型。
您需要转换引用值或将其分配给实现Closeable
的类型的变量。
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
然后您可以正常调用close()
appContext.close();
关于java -eclipse-资源泄漏 : 'appContext' is never closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473102/