Junior — Middle
Is it possible to implement a Spring component that behaves both as a singleton and as a prototype, and how to do it?
sobes.tech AI
Answer from AI
In Spring, by default, beans are either singletons or prototypes, but you cannot declare a bean as both a singleton and a prototype at the same time.
However, it is possible to implement a singleton bean that creates new instances of a prototype internally upon request.
How to do this:
- Define a singleton bean (by default).
- Define a prototype bean.
- Inject
ObjectProviderorApplicationContextinto the singleton bean to obtain new instances of the prototype on demand.
Example with ObjectProvider:
@Component
@Scope("singleton")
public class SingletonBean {
private final ObjectProvider<PrototypeBean> prototypeBeanProvider;
public SingletonBean(ObjectProvider<PrototypeBean> prototypeBeanProvider) {
this.prototypeBeanProvider = prototypeBeanProvider;
}
public void usePrototype() {
PrototypeBean prototype = prototypeBeanProvider.getObject();
prototype.doSomething();
}
}
@Component
@Scope("prototype")
public class PrototypeBean {
public void doSomething() {
System.out.println("Prototype instance: " + this);
}
}
Thus, the singleton bean can create and use new instances of the prototype each time.