我是Spring Framework的新手,在执行下面的代码时,我收到了警告"资源泄漏:' context'从未关闭"
package com.programmingtechie.examples;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class Main {
@SuppressWarnings("deprecation")
public static void main(String[] args){
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
User user = (User)factory.getBean("user");
System.out.println("This Text is using BeanFactory");
System.out.println("My Name is "+user.getName());
System.out.println("My Age is "+user.getAge());
System.out.println("My Height is "+user.getHeight());
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User contextUser = (User)context.getBean("user");
System.out.println("This Text is using ApplicationContext");
System.out.println("My Name is "+contextUser.getName());
System.out.println("My Age is "+contextUser.getAge());
System.out.println("My Height is "+contextUser.getHeight());
// ((ConfigurableApplicationContext) context).close();
}
}
我知道如果我取消注释((ConfigurableApplicationContext) context).close();
行,警告就会得到解决。但我找到了解决警告信息的另一种方法here,我不知道这种行为的原因。以下代码如何解决资源泄漏警告?
package com.programmingtechie.examples;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class Main {
private static ApplicationContext context;
@SuppressWarnings("deprecation")
public static void main(String[] args){
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
User user = (User)factory.getBean("user");
System.out.println("This Text is using BeanFactory");
System.out.println("My Name is "+user.getName());
System.out.println("My Age is "+user.getAge());
System.out.println("My Height is "+user.getHeight());
context = new ClassPathXmlApplicationContext("beans.xml");
User contextUser = (User)context.getBean("user");
System.out.println("This Text is using ApplicationContext");
System.out.println("My Name is "+contextUser.getName());
System.out.println("My Age is "+contextUser.getAge());
System.out.println("My Height is "+contextUser.getHeight());
}
}
答案 0 :(得分:3)
在第一种情况下,上下文的范围仅限于main方法。因此,该工具假定上下文仅由main方法使用,因此应在方法结束时关闭。
在第二种情况下,将上下文设置为静态变量,这意味着上下文可用于类中的所有静态方法,而不再局限于main方法的范围。因此,该工具不能假设它应该在方法结束时关闭,因此它不再发出警告。
这并不意味着第二个代码比第一个代码更好,相反。非最终静态变量通常是一种设计气味。由于上下文没有理由暴露在主方法之外,因此它不应该是:变量的范围越小越好。