2

If we create a new another bean with different id in the same xml for the same class, will spring produce another singleton bean(in same ApplicationContext)? As per my understanding there should be only one instance of the bean in single ApplicationContext.

Below example-

<bean id="bean1" class="com.myCompany.myPackage.MyClass" scope="singleton" />   
<bean id="bean2" class="com.myCompany.myPackage.MyClass" scope="singleton" />   
hardeep thakur
  • 311
  • 3
  • 9

2 Answers2

4

To keep it short: No, the singleton only says that you'll have: "one shared instance, which will be returned by all calls to getBean with the given id" (that's what the documentation states).

So, you can do any number of calls to application context and obtain "bean1" and you'll always get the same instance, but if you call by "bean2" id, you'll get another instance.

The "singleton" says that you'll have only one object. Now in a non-Spring application, you'll have it usually per JVM. But in spring application, let the framework manage this. So usually you'll want to define only one class like "MyClass" with a scope singleton.

When dependency management container (Spring in this case) manages singletons, it has a lot of advantages over the 'regular' singleton. Just to name a few:

  • Much easier to test
  • You always know when the object is created and when it becomes subject to garbage collector
  • No static code (the Spring driven singleton is just a regular bean with no statics)

But in general it's not directly related to your question.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

I did have this same question just in a different context of Spring's singleton vs. Java's singleton and I found this answer provided by 'Dexter' in this link more subtle and easy to understand.

Also, this blog here provides a perfect example for the same which is backed by the official spring documentation for better-detailed understanding.

Hope these pointers help. Thanks.

Aniket
  • 303
  • 5
  • 11