Ravi Kukreja
Ravi Kukreja

Reputation: 146

Spring bean scope : singleton and Prototype

Case 1 : Suppose we are injecting singleton bean inside prototype bean then how many instances will be created if we call prototype bean.

Consider the scenario :-

<bean id="a" class="A" scope="prototype">
 <property name="b" ref="b">
</bean>

<bean id="b" class="B">

Case 2: Suppose we are injecting Prototype bean inside singleton bean then how many instances will be created if we call singleton bean.

Consider the scenario :-

<bean id="a" class="A" >
  <property name="b" ref="b">
</bean>

<bean id="b" class="B" scope="prototype">

Upvotes: 1

Views: 288

Answers (2)

Sundararaj Govindasamy
Sundararaj Govindasamy

Reputation: 8495

I am answering a part of your question.

Case2: Singleton beans with prototype-bean dependencies

With this configuration, it is expected that when ever you fetch A from application context, it will be wired with a new B as we declared the B bean is of prototype scope. But this will not happen.

When the application context gets initialized, it sees that A is a singleton bean and initializes it to the context after wiring it with all the dependencies set. So from then onwards when we request context for A, it return the same bean every time, So you will also get the same B everytime.

You can solve/overcome this by using Lookup method injection. Refer this article.

Upvotes: 1

Serge
Serge

Reputation: 626

The singleton bean will always refer to the same object. The prototype will have as many instances created as many times that bean is referenced. The use cases you provided don't change this paradigm.

Upvotes: 0

Related Questions