Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton design pattern vs Singleton beans in Spring container

As we all know we have beans as singleton by default in Spring container and if we have a web application based on Spring framework then in that case do we really need to implement Singleton design pattern to hold global data rather than just creating a bean through spring.

Please bear with me if I'm not able to explain what I actually meant to ask.

like image 646
Peeyush Avatar asked Apr 14 '10 13:04

Peeyush


People also ask

What is the difference between Singleton pattern and singleton bean in Spring?

Spring Singleton is very different from Singleton pattern. Spring guarantees to create only one bean instance for given bean id definition per container. Singleton pattern ensures that one and only one instance is created per ClassLoader.

Does Spring use Singleton pattern?

Singleton pattern says that one and only one instance of a particular class will ever be created per classloader. The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

Is singleton from Spring container thread safe?

Singleton beans does not provide thread safety and now you know that instance variables usage may lead to unexpected result, you have 2 options to solve the same : Don't use instance variables in multithreaded environment.


1 Answers

A singleton bean in Spring and the singleton pattern are quite different. Singleton pattern says that one and only one instance of a particular class will ever be created per classloader.

The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

Even though the default scope is singleton, you can change the scope of bean by specifying the scope attribute of <bean ../> element.

<bean id=".." class=".." scope="prototype" /> 
like image 125
user184794 Avatar answered Oct 25 '22 00:10

user184794