If we create beans of two class one having singleton scope and other having prototype scope. If singleton bean refers to prototype bean how many instances will be created? What will happen internally?
-
An instance of the prototype bean will be created every time when an instance of that bean is required. So, if you have 2 singleton beans that require (depend on) the prototype bean, you will have 2 instances of the prototype bean. – Dimitar Spasovski Oct 08 '18 at 08:31
1 Answers
Spring was born as IoC (Inversion Of Control) framework. From documentation:
IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using a direct construction of classes, or a mechanism such as the Service Locator pattern.
In your case: if A is singleton object that referrers a B object scoped prototyped, B will be instantiated once, because A will invoke it only a time (during its creation).

- 4,690
- 4
- 34
- 65