Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Bean Scopes

 
Rajat Sharmanaive
Ranch Hand
Posts: 41
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
I am new to Spring. Reading through a book and docs on net. I have a query with respect to bean scoping. As we know, the default scope in spring is singleton. As per my understanding, this means that only one instance of the bean will be created and shared whenever required. Required means either being wired into another bean or directly called through getBean method. Please correct if there is anything incorrect here.
Now please look at the following code.


All the beans (especially, "owner" bean) are default scoped as singleton. In a sample application however when I access owner via greetingService and useowner respectively, changes made by one are not reflected in the other. Aren't these two sharing a "single" owner instance?


If only one instance of owner is created then why this behavior. Is it one instance per container or something like one instance per "class type" per container. I am confused. I hope there isn't any basic java polymorphism stuff here that I am not getting. Please help.
 
Rishi Shehrawat
Ranch Hand
Posts: 218
Hibernate Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are two different instances. The first instance ( useOwner) was reterieved from Spring & then you replaced useOwner with tempOwner. So changes made to tempOwner will not get reflected to useOwner.By setting Owner bean in greetingService you have created 2 instances of Owner bean. UseOwner has the instance that was created by Spring & greetingService has instance created by you. What you have done in not recommended, instead of replacing the complete bean reference you should reterieve the instance from Spring & then set the property.
 
Rajat Sharmanaive
Ranch Hand
Posts: 41
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rishi

Thanks for the reply. Yes it was quite obvious there, i should have noticed it. I have manually replaced "owner bean" in greetingService with another bean that i created. But can you please elaborate this.
What you have done in not recommended, instead of replacing the complete bean reference you should retrieve the instance from Spring & then set the property.

I mean I am sure it is not recommended. But the latter part. Do you want me to do something like:

. So that I am modifying the single existent bean, rather than adding new beans.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic