I am new to Spring and I am currently using it in one of my projects. I learned that the Spring container holds all the beans and the scope of all the beans is "singleton"
by default. I can change the scope either in the application-context.xml
file or using the annotation @Scope
.
I furthermore learned that if a class has the scope "prototype"
, the Spring container will instantiate a new object of this class whenever needed.
What I don't understand: How is garbage collection handled. Will the created objects be garbage collected if they are no longer required or will they still be kept in the container. Obviously, I do not want many objects to be created and kept in order to keep memory usage low.
Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext ). Scopes a single bean definition to a single object instance per Spring IoC container.
Singleton beans are created when the Spring container starts and are destroyed when the Spring container stops. The reason is spring container always maintains a reference to it while it is also manually referenced anywhere in your code.
Singleton is the default scope for a Bean, the one that will be used if nothing else is indicated. This scope implies that Spring container will create an only shared instance of the class designated by this bean, so each time the Bean is required the same object will be injected.
From Spring documentation (3.5.2 The prototype scope):
In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.
Simply put - once you create and obtain a reference to prototype
scoped bean, it is the only reference existing in the JVM. Once this references gets out of scope, the object will be garbage collected:
void bar() {
Object foo = ctx.getBean("foo")
}
The moment you leave bar()
method there aren't any other references to new instance of foo
, which means it is eligible for garbage collection. The consequence of this model is:
Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.
The container doesn't keep a reference to instantiated beans, the code that's using them does.
If nothing else references the bean (roughly), it's eligible for GC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With