jQuery in Action, 3rd edition
The moose likes Spring and the fly likes Spring Singleton Bean Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Spring Singleton Bean Query" Watch "Spring Singleton Bean Query" New topic

Spring Singleton Bean Query

Vaibhav G Garg
Ranch Hand

Joined: Sep 23, 2011
Posts: 141

I am relatively new to Spring Framework. As the beans are singleon in Spring Framework (By Default) and suppose if I keep them singleton throughout the application, and these bean objects will have some state (by assigning some values to the instance variables) for one user, then won't it impact the other user since the bean is singleton but the values may be required to be different for other user? How such a scenario is handled in Spring framework. For Example, one page is accessed by one user and the bean will have some properties for this page set and the same page is accessed by other users then how the singleton bean instance is shared across different users?

Bill Gorder

Joined: Mar 07, 2010
Posts: 1682

You would rarely (if ever) have a singleton Spring bean that contains state. The instance variables in Spring beans are typically other (stateless) Spring beans like services and repositories. For the objects you were describing the beans would be scoped session, request or prototype, or perhaps would not be Spring managed beans at all. They would definitely not be sngleton.

[How To Ask Questions][Read before you PM me]
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 607

While not directly related to the question - Spring Singleton's are not Singleton's as defined in the GOF pattern. A spring singleton is merely a "single" object of the class given a name (one instance) - you can create "multiple" instances by giving each instance its own name.

The Spring singleton pattern leads to easier development because,

a) For most objects what you usually need is a singleton once initialized - JDBCTemplate - once you create an instance pointing to a database - you don't usually need any other "state" in the object. Classes designed against this principle usually cause programing errors (e.g. SimpleDateFormat)

b) having a single "state-full" object is useful in many scenario's. For e.g. in a Batch Job I need to track count of records processed. The processor keeps adding one for each record it processes (single threaded process, for multi-thread I need to synchronize on the object). Either was the "single" state object that keep track of multiple objects does work very well.

Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
I agree. Here's the link: http://aspose.com/file-tools
subject: Spring Singleton Bean Query
jQuery in Action, 3rd edition