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

前端 未结 17 513
伪装坚强ぢ
伪装坚强ぢ 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:42
    Object obj = context.getBean("bean");
    if(bean instanceof Bean) {
        Bean bean = (Bean) obj;
    }
    

    In my case leak disappears

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

    A simple cast solves the issue:

    ((ClassPathXmlApplicationContext) fac).close();
    
    0 讨论(0)
  • 2020-12-04 17:43

    Downcast the context to ConfigurableApplicationContext.

    ((ConfigurableApplicationContext)context).close();
    
    0 讨论(0)
  • 2020-12-04 17:47

    for ApplicationContext you can't use close() method because this method doesn't define int it but instead you can use:(ClassPathXmlApplicationContext(context)).close()

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

    As the Application context has an instance of ClassPathXmlApplicationContext and the same has a close() method. I would simply CAST the appContext object and invoke the close() method as below.

    ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
    //do some logic
    ((ClassPathXmlApplicationContext) appContext).close();
    

    This will fix the Resource Leak warning.

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

    This worked out best for me.

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    
    public class Test {
    
         private static ApplicationContext con;
    
         public static void main(String[] args) {
    
             con = new ClassPathXmlApplicationContext("config.xml");
    
             Employee ob = (Employee) con.getBean("obj");
             System.out.println("Emp Id " + ob.getEmpno());
             System.out.println("Emp name " + ob.getEmpname());
        }
    }
    
    0 讨论(0)
提交回复
热议问题