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

前端 未结 17 609
伪装坚强ぢ
伪装坚强ぢ 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:01

    close() is not defined in ApplicationContext interface.

    The only way to get rid of the warning safely is the following

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(...);
    try {
        [...]
    } finally {
        ctx.close();
    }
    

    Or, in Java 7

    try(ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(...)) {
        [...]
    }
    

    The basic difference is that since you instantiate the context explicitly (i.e. by use of new) you know the class you are instantiating, so you can define your variable accordingly.

    If you were not instantiating the AppContext (i.e. using the one provided by Spring) then you couldn't close it.

提交回复
热议问题