Tag Archives: The context problem

Spring ApplicationContext – Resource leak: ‘context’ is never closed

Compiling environment: Eclipse

Problem: in spring MVC applications, I use the following method to initialize variables in one of the service classes

ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj=(HelloWorld) context.getBean("helloWorld");
obj.getMessage();

In the first line of the above code, the ‘context’ variable generates a warning. The warning is as follows:

Resource leak: 'context' is never closed

Solution: because ApplicationContext has an instance of classpathxmlapplicationcontext, it has a close () method. We just need to throw the context object and call the close () method, as shown below.

((ClassPathXmlApplicationContext) context).close();

In addition, if the ApplicationContext uses an abstractapplicationcontext instance, you need to throw the context object of that type and call the close () method.

import org.springframework.context.support.AbstractApplicationContext;
    ...
    ...
    ...
    ...
((AbstractApplicationContext) context).close();