【Spring】在Java使用Spring时的Resource leak: 'applicationContext' is never closed警告

在Java使用Spring的时候,在定义完Spring的核心文件,用准备使用ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");来启动Spring的时候,要是不处理,在eclipse必然会出现Resource leak: 'applicationContext' is never closed的警告。虽然程序是毫无疑问地能读完,但是这个警告看着注定不爽。

如下图所示:


这是因为,这个applicationContext使用完和Scanner等流一样,用完需要关闭,正如这个警告提示的字面意思的一样。

然而,你会发现,在applicationContext中并没有包含关闭方法,如下图所示:


这是因为Spring3.x将这个方法藏在ConfigurableApplicationContext这个类里面了。

引入org.springframework.context.ConfigurableApplicationContext这个类,同时最后加一句((ConfigurableApplicationContext)applicationContext).close();这个警告则可以完美去除了,也就是上面的程序变成了:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

public class Client {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		// 中间,spring要做的一系列事情……
		((ConfigurableApplicationContext) applicationContext).close();
	}

}



猜你喜欢

转载自blog.csdn.net/yongh701/article/details/78500954
今日推荐