
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Singleton and Prototype Bean Scope
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. | Key | Singleton bean scope | Prototype 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"/>