• 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 ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
  • Himai Minh
  • Carey Brown
  • salvin francis

Different Objects referring to same property|field

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.

[Thumbnail for JavaAnnotation.PNG]
Output Image
Posts: 4899
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
  • 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


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
    Bookmark Topic Watch Topic
  • New Topic