Singleton scope in spring

This is by default scope in spring . Only one shared instance of a singleton bean is managed, and all requests for beans with an ID that match that bean definition result in that one specific bean instance being returned by the Spring container , in short “one bean per bean id in a container“.

Suppose, I have a bean class Family. I have defined two beans from this class in bean definition, like:

<bean id="id1" class="com.example.Family"/> 
<bean id="id7" class="com.example.Family"/>

So when ever I try to get the bean with id “id1”,the spring container will create one bean, cache it and return same bean where ever referred with id1. If I try to get it with id7, another bean will be created from Sample class, same will be cached and returned each time you referred that with id7.

This is unlikely with Singleton pattern. In Singleton pattern one object per class loader is created . However in Spring, making the scope as Singleton does not restrict the container from creating many instances from that class. It just restricts new object creation for the same ID again, returning previously created object when an object is requested for the same id.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: