This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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 javapolymorphism stuff here that I am not getting. Please help.
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.
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.