java中 never closed_【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的警告。虽然程序是毫无疑问地能读完,但是这个警告看着注定不爽。

如下图所示:

0818b9ca8b590ca3270a3433284dd417.png

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

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

0818b9ca8b590ca3270a3433284dd417.png

这是因为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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值