Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean scope. Singleton and Prototype

Tags:

java

spring

Suppose two classes ClassA and ClassB. Lets suppose ClassB is dependent on ClassA. On configuration file, if we define scope of ClassA to be singleton and that of ClassB to be Prototype then what happens to instance of ClassB each time we create a bean instance of ClassA? Will the same ClassB instance gets returned or new instance is created each time instance of ClassA is returned?

Thank you!!!

like image 293
asp_NewBee Avatar asked Oct 15 '13 13:10

asp_NewBee


2 Answers

if ClassB is prototype, a newly instance of ClassB is always created, it does not take care of other classes at creation.

So ClassB being prototype and ClassA singleton, you could have N instances of ClassB and only 1 of ClassA in your application at some point.

In your case, as only one instance of ClassA will exist on your application life-cycle, it will only have one instance ClassB which will be different to any other ClassB referenced by other beans in your application

like image 52
RamonBoza Avatar answered Oct 17 '22 06:10

RamonBoza


What happens to instance of ClassB each time we create a bean instance of ClassA?

Since ClassA is a singleton, an single instance will be shared among all the instances of ClassB.

Will the same ClassB instance gets returned or new instance is created each time instance of ClassA is returned?

I think here you meant Will the same ClassA instance gets returned or new instance is created each time instance of ClassB is returned?

Everytime an instance of ClassB is created the shared ClassA instance will be (re-)used.

like image 35
Konstantin Yovkov Avatar answered Oct 17 '22 06:10

Konstantin Yovkov