Take the 2-minute tour ×
  1. When is a Spring container (XMLBeanFactory) gracefully unloaded by Spring?
  2. What happens when the application is running but the only handler to the BeanFactory goes out of scope?
  3. What is the ideal way to load a Spring Container? Is doing handler = new BeanFactory() the right approach?

When container goes out of scope, we would indeed expect the close() method to be called which would in turn release all the held resources. But that does not happen! I encountered a case where I had spring containers going out of scope but still memory getting full (OutOfMemory error). The reason was that the SessionFactory objects created by my Spring containers never got garbage collected as they are created as static. This implies that close()->destroy() was never called when containers went out of scope. Makes me believe that there is a leak issue with Spring itself.

share|improve this question

2 Answers 2

up vote 2 down vote accepted
  1. This depends on how you're instantiating it. I a webapp, this is typically done at context shutdown. On the command line, you have to specifically close the context (via the "close" method on "AbstractApplicationContext"
  2. Same as anything else that falls out of scope. Not sure if the "close" method is part of the finalizer phase or not. I would hope the finalizer would trigger the destroy phase.
  3. As someone else said, don't use BeanFactory directly. Create an ApplicationContext. The most common way for web apps is the ContextLoaderListener, and for command line programs would be ClassPathXmlApplicationContext.

// Keep a specific type, so we can call the "close" method later since it's // not part of the ApplicationContext interface itself. ClasspathXmlApplicationContext context = new ClasspathXmlApplicationContext(new String[] { "applicationContext.xml });

and then later on you close it:


For webapps:


share|improve this answer
Thanks Matt. (1) and (3) were quite helpful. For (2), I have some genuine concerns. Please see the update. –  Leo May 30 '12 at 8:26
And if close() is not part of the finalizer, then who triggers this method when the web app context shuts down or when the JVM shuts down? –  Leo May 30 '12 at 9:41

BeanFactory is the ancient way to do things in Spring. The more modern way to instantiate a Spring context is through the ApplicationContext interface. For reference, read

4.2.2 Instantiating a container

If you are going to use Spring in a Web App, also read

4.14.4 Convenient ApplicationContext instantiation for web applications

share|improve this answer
BeanFactory is not more ancient than ApplicationContext. They were created at approximately the same time. ApplicationContext is an enriched version of a generic BeanFactory and contains messaging, events, hierarchies, lifecycles etc. –  Niels Bech Nielsen Apr 10 '13 at 9:49

Your Answer


