Difference between singleton and prototype bean scope.

SpringObject Oriented ProgrammingProgramming

Spring framework supports five types of bean scope −

  • Singleton

  • Prototype

  • Request

  • Session

  • Global Session

As per the spring documentation −

Singleton − It returns a single bean instance per Spring IoC container. 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.

Spring singleton is different than Java singleton. In java, one instance of the bean is created per JVM whereas in spring, one instance of the bean is created per application context.

Proptype −

As per 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.

Sr. No.KeySingleton bean scopePrototype bean scope
1
Number of Instances
It returns a single bean instance per Spring IoC container. 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
A new object is created each time it is injected/looked up. It will use new X() each time
2
Scope
In Spring default scope of the bean is Singleton
It is not default scope of the beans in Spring
3
Bean Creation
It is created during the initialization of the application context
It is created whenever it is called.
4
State/Stateless
It is used for all the beans which are stateless
It is used for beans which are stateful by nature

Example of Singleton and Prototype

<bean id="xyzService" class="com.xyz.XyzService" scope="singleton"/>

<bean id="xyzService" class="com.xyz.XyzService" scope="prototype"/>
raja
Published on 09-Sep-2020 12:28:19
Advertisements