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

前端 未结 17 608
伪装坚强ぢ
伪装坚强ぢ 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 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.

提交回复
热议问题