• Post Reply Bookmark Topic Watch Topic
  • New Topic

Different Objects referring to same property|field  RSS feed

 
abdul mobeen
Greenhorn
Posts: 3
Hibernate PHP Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have created a simple Spring Demo to learn spring. I created two objects of class Asian from spring container. I set of value of first object to Ali and second to Usman but when I print them the value of both of the objects is usman. I didn't expect that. Please can anybody tell me whats the problem . Below is the code:




--------------------------------------


--------------------------------

--------------------------------------



Output is below :

My name is : Usman
My name is : Usman
Usman -
Usman -

---------------------------------------
I think out put should be like



My name is : Ali
My name is : Usman
Ali -
Usman -


Please help.


JavaAnnotation.PNG
[Thumbnail for JavaAnnotation.PNG]
Output Image
 
Tim Cooke
Marshal
Posts: 3715
198
Clojure IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By default Spring beans are created as Singletons, which means there is only one instance of it. So when you do:

You are creating two references to the same object. Hence, when you do this:

You first set the object name to "Ali", and then immediately change the name of the same object to "Usman".
 
Sergej Smoljanov
Ranch Hand
Posts: 472
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By default spring use singleton scope.
this mean that when you retrieve bean


if you want  - you can change this behavior.
you must specify other scope:
scope="prototype" add in xml in bean definition

or


http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes - you can read more here

Also pay attention when you inject object with prototype in singleton bean.
And pay note when you try configure
@PreDestroy method, container do not manage prototype bean destroy behavior.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!