1

In Spring config file, I have created two bean for the same class i.e.

<bean id="emp1" class="Employee">
    <property name="age" value="10"></property>
</bean>

<bean id="emp2" class="Employee">
    <property name="age" value="15"></property>
</bean>

and scope for both is by default 'singleton' but when I print Employee object its showing two different objects. How is this possible? I mean If the bean scope is singleton then how it's creating two different objects ?

1 Answer 1

7

It should return 2 employees. Singleton has a slightly different meaning in spring - it's not about guaranteeing 1 instance per class. It just means every time you call "context.getBean("emp1")" you'll get the same object, as opposed to "prototype" which means getting a different instance each time to call context.getBean("emp1")

try this

Object x1=context.getBean("emp1");
Object x2=context.getBean("emp1");

If "emp1" is singleton you'll get the same reference. If prototype you'll get two separate instances.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.