Pratik Shelar
Pratik Shelar

Reputation: 3212

Spring singleton class instances created?

I have the following spring configuration.

<bean id="abcService1" class="com.service.ABCServiceImpl" />
<bean id="abcService2" class="com.service.ABCServiceImpl" />

Will spring create 2 instances with different ids for the above configuration?If yes then although both the bean definitions are singleton we still have 2 instances of the same object in the context. Would that mean that its not a singleton any more?

Upvotes: 1

Views: 6715

Answers (2)

Łukasz Rzeszotarski
Łukasz Rzeszotarski

Reputation: 6140

Yes. Two seperate instances will be created. Yes this is not a singleton anymore in a classical meaning (one instance per JVM) - (if ever was), however the created bean (each of them) has a singleton scope (in a Spring meaning). If you really want to assure that an object of a given class will be always a singleton (only one instance per JVM) see Correct way of making a singleton a Spring bean.

But the question is if you really need 'the real singleton'?!

See http://docs.spring.io/spring/docs/3.2.1.RELEASE/spring-framework-reference/html/beans.html#beans-factory-scopes

Upvotes: 2

Sajan Chandran
Sajan Chandran

Reputation: 11487

Yes, the object will no more be Singleton.

By default all Spring injected beans are Singleton, but if you define the same bean twice with two different ids then Spring will create two instances.

Upvotes: 1

Related Questions