Spring ApplicationContext - Resource leak: 'context' is never closed

前端 未结 17 514
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 17:15

In a spring MVC application, I initialize a variable in one of the service classes using the following approach:

ApplicationContext context = 
         new C         


        
相关标签:
17条回答
  • 2020-12-04 17:52
    import org.springframework.context.ConfigurableApplicationContext;
    
    ((ConfigurableApplicationContext)ctx).close();
    
    0 讨论(0)
  • 2020-12-04 17:54

    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();

    0 讨论(0)
  • 2020-12-04 17:55

    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();
    
           }
    }
    
    0 讨论(0)
  • 2020-12-04 17:56

    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();
    
    0 讨论(0)
  • 2020-12-04 17:57

    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

    0 讨论(0)
  • 2020-12-04 18:00

    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.

    0 讨论(0)
提交回复
热议问题