In simple words Singleton in Java means only one instance of a class in JVM. Whereas in Spring it is one instance of a class in the Spring container (reason is, single JVM can contain multiple Spring Container).
In Java, when we implement a Singleton class we ensure that every-time the one and only instance of the class be returned, whenever accessed. This can be achieved by the below program.
public final class MySingleton {
private static MySingleton mySingleton = new MySingleton();
private MySingleton() {
}
public static MySingleton getInstance() {
return mySingleton;
}
}
In case of spring if we define two beans of the same class we get two instance in our Java application when those beans are accessed.
<bean id="employee1" class="test.demo.Employee" scope="singleton"></bean>
<bean id="employee2" class="test.demo.Employee" scope="singleton"></bean>
It is true that, context.getBean("employee2");
always returns the same instance. At the same time, the default scope in Spring is Singleton. My question is, doesn't the above code defies the purpose of Singleton?
Even if we define scope="singleton"
in multiple bean declaration of the same class why does Spring always return a new instance?