I have seen people getting confused between singleton scope vs singleton design pattern. Basically, there is a bit difference between these two.
Singleton scope: The spring support five different scopes and it is used to decide which type of bean instance should be returning from Spring container back to the caller. One of the scope is Singleton and the by default scope too. It returns a single bean instance per Spring IoC container.
<bean id=”object1” class=“com.package.classname”/>
When I said, single bean instance per spring Ioc Container i.e. you will always get the same object regardless of the number of call of the same bean but if you declare another bean for the same class then you will get another object for another bean.
Let’s understand this with an example:
<bean id=”object1” class=“com.package.classname”/>
<bean id=”object2” class=“com.package.classname” scope=”prototype”/>
<bean id=”object3” class=“com.package.classname”/>
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(APP_FILE);
Classname name1 = (Classname) context.getBean(“object1”);
Classname name2 = (Classname) context.getBean(“object2”);
Classname name3 = (Classname) context.getBean(“object3”);
name1==name1 // true, object1 is singleton, calling again n again will give the same object.
name2==name2 //false, object2 is prototype, calling again n again will give the different object
name1==name3 // false, object1 & object3 is singleton but two different bean.
So, the question arise how will you achieve the Singleton design pattern in Spring?
Spring framework provides facility to inject bean using factory method i.e. that returns an instance of its own class and can be used in singleton design pattern.
public class Singleton {
private static volatile Singleton instance = null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
<bean id="object4" class="com.package.Singleton" factory-method="getInstance"/><bean id="object5" class="com.package.Singleton" factory-method="getInstance"/>
Singleton singleton1= (Singleton) context.getBean(“object4”);
Singleton singleton2= (Singleton) context.getBean(“object5”);
singleton1==singleton1 // true, object1 has singleton scope, calling again n again will give the same object.
singleton1==singleton2 //true, Class is a singleton and we are getting an object from getInstance using factory-method.
Conclusion: Singleton scope is a bit different from a single design pattern, Returns a single bean per Spring Ioc Container whereas singleton design pattern will always return the same object.
Singleton scope can be useful where you are creating multiple datasource in your application where each datasource point to a different object.
You can download the code source from my GitHub repository.
Happy coding!!!