views:

744

answers:

3

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.

A: 

Singleton scope in Spring means that this bean will be instantiated only once by Spring. In contrast to the prototype scope (new instance each time), request scope (once per request), session scope (once per HTTP session).

Singleton scope has technically noting to do with the singleton design pattern. You don't to implement your beans as singletons for them to be put in the singleton scope.

lexicore
Correct me if I'm wrong so according to you if I need to implement any object as singleton so there is no need to implement singleton pattern. Creating that bean using Spring will work. I'm a bit confused now with my understanding related to Singleton Design pattern and Singleton scope in Spring framework.
Peeyush
Spring does not force you to use the Singleton pattern.
lexicore
+2  A: 

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

THe scope of 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 in Singleton.

Eventhough 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" />
Thanks, this really clears all my doubts.
Peeyush
A: 

"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.

lwpro2