Junior — Middle
È possibile implementare in Spring un componente che si comporta sia come un singleton che come un prototipo, e come farlo?
sobes.tech AI
Risposta dell'AI
In Spring, per impostazione predefinita, i bean sono singleton o prototype, ma non è possibile dichiarare un bean come entrambi contemporaneamente.
Tuttavia, è possibile implementare un bean singleton che crea nuove istanze di prototype su richiesta.
Come farlo:
- Definire un bean singleton (predefinito).
- Definire un bean prototype.
- Iniettare nel singleton un
ObjectProvideroApplicationContextper ottenere nuove istanze di prototype quando necessario.
Esempio con 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("Istanza prototype: " + this);
}
}
In questo modo, il singleton può creare e utilizzare nuove istanze di prototype ad ogni chiamata.