警告:Spring ApplicationContext - Resource leak: 'context' is never closed的处理

来源:互联网 发布:手写图片识别软件 编辑:程序博客网 时间:2024/04/30 12:38

在一次代码调试中,发现了一条Warning提示:
Spring ApplicationContext - Resource leak: ‘context’ is never closed

看下面的代码:

<!-- 代码片段 -->ApplicationContext ctx =          new ClassPathXmlApplicationContext("classpath:userLibrary.xml");service = ctx.getBean(UserLibrary.class);<!-- 代码片段 -->

上面的代码会产生一条Warning信息:

Resource leak: 'ctx' is never closed

这个警告是怎么产生的呢?

ctx对象没有类似close或者destroy方法。这个警告又试图告诉开发者什么信息呢?

处理这个警告的一种方法:

public class MainApp {    /*     * 这种处理方法并不是很恰当。因为放大了context的限定范围。     */    private static ApplicationContext context;    public static void main(String[] args) {        context = new ClassPathXmlApplicationContext("Beans.xml");        HelloWorld objA = (HelloWorld) context.getBean("helloWorld");        objA.setMessage("I'm object A");        objA.getMessage();        HelloWorld objB = (HelloWorld) context.getBean("helloWorld");        objB.getMessage();    }}

ClassPathXMLApplicationContext super class implements ConfigurableApplicationContext which contains the close() method. We can typecast the context into ConfigurableApplicationContext to call the close() method, it frees the resources. Simply also we can do like ((ClassPathXmlApplicationContext)ctx).close();

另外一种处理方法:

import org.springframework.context.ConfigurableApplicationContext;((ConfigurableApplicationContext)ctx).close();
0 0
原创粉丝点击