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

来源:互联网 发布:绝爱后宫我知帝王心txt 编辑:程序博客网 时间:2024/05/01 21:26

在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();}}



阅读全文
0 0