In a spring MVC application, I initialize a variable in one of the service classes using the following approach:
ApplicationContext context =
new C
Yes, interface ApplicationContext
doesn't have close()
method, so I like to use class AbstractApplicationContext
to use that close
method explicitly and also here you can use your Spring Application configuration class using annotation instead of XML
type.
AbstractApplicationContext context = new AnnotationConfigApplicationContext(SpringAppConfig.class);
Foo foo = context.getBean(Foo.class);
//do some work with foo
context.close();
your Resource leak: 'context' is never closed
warning is gone now.
close()
is not defined in ApplicationContext
interface.
The only way to get rid of the warning safely is the following
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(...);
try {
[...]
} finally {
ctx.close();
}
Or, in Java 7
try(ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(...)) {
[...]
}
The basic difference is that since you instantiate the context explicitly (i.e. by use of new
) you know the class you are instantiating, so you can define your variable accordingly.
If you were not instantiating the AppContext (i.e. using the one provided by Spring) then you couldn't close it.
If you are using the ClassPathXmlApplicationContext then you can use
((ClassPathXmlApplicationContext) context).close();
to close the resource leak problem.
If you are using the AbstractApplicationContext then you can cast this with close method.
((AbstractApplicationContext) context).close();
It depends on the type of context using in the application.
try this. you need to apply cast to close applicationcontext.
ClassPathXmlApplicationContext ctx = null;
try {
ctx = new ClassPathXmlApplicationContext(...);
[...]
} finally {
if (ctx != null)
((AbstractApplicationContext) ctx).close();
}
Even I had the exact same warning, all I did was declare ApplicationContext
outside the main function as private static
and ta-da, problem fixed.
public class MainApp {
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();
}
}