This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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.
Joined: May 08, 2006
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);
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?
Joined: Jan 22, 2007
The above code should return you the same instance.
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.