Junior — Middle
What is the number of prototype beans injected into a singleton bean in Spring?
sobes.tech AI
Answer from AI
In Spring, if a singleton bean directly injects a prototype bean through regular autowiring, then the prototype bean is created once when the singleton bean is created and reused — in other words, only one instance of the prototype bean is effectively injected.
To obtain a new instance of the prototype bean on each call, you need to use special mechanisms, such as:
ObjectFactoryorProviderto request a new instance- a method annotated with
@Lookup
Example with ObjectFactory:
@Component
public class SingletonBean {
@Autowired
private ObjectFactory<PrototypeBean> prototypeBeanFactory;
public void doSomething() {
PrototypeBean prototypeBean = prototypeBeanFactory.getObject();
prototypeBean.action();
}
}
Thus, the number of prototype beans injected into the singleton bean depends on the injection method: with direct injection — one instance, using a factory — as many new instances as requested.