我是 Spring 框架的新手,在执行下面的代码时,我收到警告“资源泄漏:‘上下文’从未关闭”
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());
}
}
第一种情况,上下文的范围仅限于main方法。因此,该工具假设上下文仅由主方法使用,因此应在方法结束时关闭。
在第二种情况下,将上下文设置为静态变量,这意味着该上下文可供类中的所有静态方法使用,而不再局限于 main 方法的范围。因此该工具不能再假设它应该在方法结束时关闭,因此它不再发出警告。
这并不意味着第二个代码比第一个代码更好,相反。非最终静态变量通常是一种设计味道。而且由于上下文没有理由暴露在 main 方法之外,所以不应该这样:变量的范围越小越好。
@SuppressWarnings("resource") ,请在警告上方尝试此操作