• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

Different Objects referring to same property|field

 
Greenhorn
Posts: 3
Hibernate Spring PHP
  • 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
 
Sheriff
Posts: 4899
318
IntelliJ IDE Python Java Linux
  • 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".
 
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.
 
It's fun to be me, and still legal in 9 states! Wanna see my tiny ad?
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic