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