Is spring default scope singleton or not?

Raj picture Raj · Jul 25, 2015 · Viewed 84.1k times · Source

Could you please explain why Spring is creating two objects for the configuration of beans shown below, since by default spring default scope is singleton?

The Spring configuration is here:

<bean id="customer" class="jp.ne.goo.beans.Customer"> 
    <property name="custno" value="100"></property>
    <property name="custName" value="rajasekhar"> </property>
</bean>
<bean id="customer2" class="jp.ne.goo.beans.Customer"> 
    <property name="custno" value="200"></property> 
    <property name="custName" value="siva"></property> 
</bean>

Answer

Nathan Hughes picture Nathan Hughes · Jul 25, 2015

Spring's default scope is singleton. It's just that your idea of what it means to be a singleton doesn't match how Spring defines singletons.

If you tell Spring to make two separate beans with different ids and the same class, then you get two separate beans, each with singleton scope. All singleton scope means is that when you reference something with the same id, you get the same bean instance back.

Here is how the Spring documentation defines singleton scope:

Only one shared instance of a singleton bean is managed, and all requests for beans with an id or ids matching that bean definition result in that one specific bean instance being returned by the Spring container.

Singleton scope means using the same id retrieves the same bean, that is all. Testing that no two ids referenced the same class would get in the way of using maps as beans, and would be complicated by proxying things with BeanFactories. For Spring to police this would involve a lot of work for little benefit, instead it trusts the users to know what they're doing.

The way to define two names for the same bean is to use an alias:

In a bean definition itself, you can supply more than one name for the bean, by using a combination of up to one name specified by the id attribute, and any number of other names in the name attribute. These names can be equivalent aliases to the same bean, and are useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself.

Specifying all aliases where the bean is actually defined is not always adequate, however. It is sometimes desirable to introduce an alias for a bean that is defined elsewhere. This is commonly the case in large systems where configuration is split amongst each subsystem, each subsystem having its own set of object definitions. In XML-based configuration metadata, you can use the element to accomplish this.

So if you add a name in the bean configuration:

<bean id="customer" name="customer2" 
    class="jp.ne.goo.beans.Customer">
</bean>

or create an alias for a bean defined elsewhere:

<alias name="customer" alias="customer2"/>

then "customer" and "customer2" will refer to the same bean instance.