In a spring MVC application, I initialize a variable in one of the service classes using the following approach:
ApplicationContext context =
new C
import org.springframework.context.ConfigurableApplicationContext;
((ConfigurableApplicationContext)ctx).close();
Casting is the correct resolution for this issue.
I faced the same issue using the below line.
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
To resolve the warning just downcast the ctx
object like below and then close it.
((AnnotationConfigApplicationContext) ctx).close();
You make the context a static variable, which means that the context is available to all the static methods in the class, and not limited to the scope of the main method anymore. So the tool can't assume that it should be closed at the end of the method anymore, so it doesn't issue the warning anymore.
public class MainApp {
private static ApplicationContext context;
public static void main(String[] args) {
context =
new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
The method close has been added to ConfigurableApplicationContext interface, so the best you can do to get access to it is:
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
"/app-context.xml");
// Use the context...
context.close();
it has a simple solution just input the Core jar into the libraries, given at this link [download the core jar files for spring][1] [1]: https://static.javatpoint.com/src/sp/spcorejars.zip
Since the app context is a ResourceLoader (i.e. I/O operations) it consumes resources that need to be freed at some point. It is also an extension of AbstractApplicationContext
which implements Closable
. Thus, it's got a close()
method and can be used in a try-with-resources statement.
try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/userLibrary.xml")) {
service = context.getBean(UserLibrary.class);
}
Whether you actually need to create this context is a different question (you linked to it), I'm not gonna comment on that.
It's true that the context is closed implicitly when the application is stopped but that's not good enough. Eclipse is right, you need to take measures to close it manually for other cases in order to avoid classloader leaks.