• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton scope problem

 
Tapan Maru
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am having a following declaration in Spring's bean file.

<bean id="a" class="com.vaannila.Person"></bean>
<bean id="b" class="com.vaannila.Person"></bean>

As I have not applied scope attribute, I expect only one instance will be created by spring for both the bean declarations.

But when I run the code, I got 2 different instances (one for each bean id) for the Persoan class having different hash codes.

I want to know how spring handles this kind of senario.
 
Piyush Mangal
Ranch Hand
Posts: 196
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Spring will create atleast one object per bean definition depending on the scope.
for singleton scope, you will get only one object per bean definiton, As you have defined 2 beans , spring will create 2 instance of the same.
The difference lies in how applicationContext.getBean("beanName") behaves , in case of singleton, multiple invocation returns you the same instance while in case of prototype ,it will give a new instance
every time you call it.
 
Tapan Maru
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Piyush for the promt reply.

My code is as follows.

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person p1 = (Person) context.getBean("a");
Person p2 = (Person) context.getBean("b");
System.out.println("P1 hash code = "+p1.hashCode());
System.out.println("P2 hash code = "+p2.hashCode());
System.out.println(p1 == p2);


Corrosponding XML is as follows.

<bean id="a" class="com.vaannila.Person"></bean>
<bean id="b" class="com.vaannila.Person"></bean>


When running the above code, I am getting 2 differeent hashcodes and also == returns false. Can you please help me explaining why it is?

"in case of singleton, multiple invocation returns you the same instance" - does it mean that multilple invocation of Person p1 = (Person) context.getBean("a"); will give me the same instance for every call if scope is Singleton and different instances if scope prototype?

Thanks
 
Piyush Mangal
Ranch Hand
Posts: 196
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



The above code should return you the same instance.
 
Sai Narasimha Reddy
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's simple. There are two bean definitions configured for the same class, the spring container will instantiate two objects. Since they're not the same (I presume you've not overrideen hashCode() and equals()) the boolean statement returns false.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic