Spring bean. Singleton and prototype

Suppose the two classes are ClassA and ClassB. Suppose ClassB is dependent on ClassA. In the configuration file, if we define the scope of ClassA as singleton and classB as Prototype, then what happens to the ClassB instance each time we instantiate the bean class of class A? Will the same instance of ClassB be returned, or will a new instance be created each time an instance of ClassA is returned?

Thanks!!!

+8
java spring
source share
3 answers

if ClassB is a prototype, a new instance of ClassB is always created; it does not care about other classes when created.

So, the prototype of ClassB and the unicast single ClassA, at some point you could have N instances of ClassB and only 1 from ClassA in your application.

In your case, since only one instance of ClassA will exist in the life cycle of your application, it will have only one instance of ClassB that will be different from any other ClassB referenced by other beans in your application

+5
source share

What happens to an instance of ClassB every time we create an instance of a class bean?

Since ClassA is singleton, a single instance will be used for all instances of ClassB .

Will the same instance of ClassB be returned, or will a new instance be created each time an instance of ClassA is returned?

I think what you meant here is the same ClassA instance will be returned or a new instance will be created each time an instance of ClassB is returned?

Each time an instance of ClassB is created, the shared instance of ClassA will be reused.

+3
source share

What happens to an instance of ClassB every time we create an instance of a class bean?

Nothing, if ClassA is singleton, it will be created only once.

Will the same instance of ClassB be returned, or will a new instance be created each time an instance of ClassA is returned?

Different instances, as this is a prototype bean. But since ClassA is singleton, it will be created in the same way each time (depends on your connection between the classes you specify)

+2
source share

All Articles