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

前端 未结 17 580
伪装坚强ぢ
伪装坚强ぢ 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: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();
    
           }
    }
    

提交回复
热议问题