Is spring default scope singleton or not?

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.

If you want a bean’s singleton-ness preserved across multiple names, that is do-able. You can have more than one name refer to the same bean, that is done by using 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" 

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.

Leave a Comment