i\'m new to spring and i read this :
Basically a bean has scopes which defines their existence on the application
Singleton: means single bean def
Singleton Scope: With Singleton scope, one and only one instance of a bean is created with the provided bean definition and for subsequent requests for the same bean, Spring container will return the same instance .
From the Spring documentation:
.. when you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object...
Example:
Lets say, we have defined a bean accountDao as below:
And another two beans, which uses this accountDao bean
Spring will initially create accountDaobean and cache it. And then for someBean as well as anotherBean, it will provide the same instance of accountDao.
Note: If no scope is specified with bean definition, Singleton is the default scope.
Prototype Scope: For prototype scope, for each request for the bean, a new instance of the bean will be created and returned. This is similar to calling new operator in java for a class.
Example:
Lets say, we have defined a bean accountDao as below:
And another two beans, which uses this accountDao bean
For someBean and anotherBean, Spring will return two separate instance of the accountDao object.
One important difference is, for prototype scope, Spring does not manage the complete lifecycle of the bean, clean up needs to be done by the client code.
From the Spring documentation:
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. 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 client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.