Difference Between Singleton Design Pattern and Spring Bean
This is a very popular interview question for Spring as well as design patterns. The answer to this question reveals the in-depth understanding of both the concepts. Does Spring’s singleton scope provides one and only one object of the class? If so, how does it handle all the requests? How it is different than Singleton Design pattern, if it is ?
The answer to this tricky question is actually simple and can only be understood if you know both the concepts completely. Reason being “Spring’s concept of a singleton bean is actually” far different from the Singleton Design pattern”.
Let’s see step by step how it is so different and what are the actual differences:
Singleton Design Pattern restricts the instantiation of a class to one object so that one and only one instance of a particular class will ever be created per Class Loader.
I am not going to discuss Singleton design pattern much in detail here as it can be found easily anywhere. The focus would be more on Spring’s Singelton Scope and the difference between both the concepts.
One Per Container
Spring Singleton is ‘per Spring IOC Container and per bean’.
The container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans and all subsequent requests and references for that bean return the cached object.
Now, we need to carefully understand that this object is single for the IoC Container and NOT the JVM or entire application.
The application itself can have multiple IoC containers as well and in that case the rule of getting same object breaks!!!
To understand the concept more clearly, we will create 2 different examples.
First one, to show how a single instance gets returned again and again by the container and what is the significance of having Singleton Scope in Spring Bean.
Second One, to show how different instances for the same bean are created even after having the scope Singleton at the time container gets re-instantiated. This example will show the multiple instances creation for the same bean but because of same IOC Container each would refer to the same one from the cache.
Sounds interesting? Lets get into the code now!!!
A Simple Bean Class Code:
A simple ApplicationContext.xml :
Java Class instantiating the container and accessing the bean
Java Class instantiating the container twice and accessing the bean :
Bean name 1 : A Simple Bean of goyalsbit.com
Bean name 2 : A Simple Bean of goyalsbit.com
Bean name 2 : null
context classloader: sun.misc.Launcher$AppClassLoader@a39137
newContext classloader: sun.misc.Launcher$AppClassLoader@a39137
So here if you see the classloader is same for both the ApplicationContext but the bean returned by both are different.
Hope the above code examples made the concept clear to you. Please share your thoughts and suggestions by writing back in comments.