• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Spring Singleton Bean Query

 
Vaibhav G Garg
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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?

Thanks.
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic