Ich muss mehrere Instanzen einer Spring Bean erstellen (nennen wir es MainPrototypeBean
), die ich mit dem prototype
Bereich tun kann. Es hängt von einigen anderen Beans ab, und ich möchte jedes Mal, wenn die Haupt-Bean erstellt wird, neue Instanzen von ihnen erstellen. Es gibt jedoch eine gemeinsame Abhängigkeit zwischen einigen der Beans, nennen wir es SharedPrototypeBean
. Wie injiziere ich die gleiche Instanz SharedPrototypeBean
in jede abhängige Beans, während auch eine neue Instanz für jede MainPrototypeBean
?Shared Prototyp Bohnen im Frühjahr
Ich bin in die Implementierung eines benutzerdefinierten Bereichs, aber ich hoffe, einen saubereren Weg zu finden. Es ist keine Option, irgendwelche der Bohnen-Singletons herzustellen, da sie zwischen verschiedenen Instanzen von MainPrototypeBean
isoliert werden müssen.
Hier ist ein Beispiel dafür, was ich zu tun habe versucht:
@SpringBootApplication
public class DIDemo {
public static void main(String[]args){
ConfigurableApplicationContext context = SpringApplication.run(DIDemo.class, args);
context.getBean(MainPrototypeBean.class);
}
@Component @Scope("prototype") static class SharedPrototypeBean {}
@Component @Scope("prototype") static class FirstPrototypeBean {
@Autowired SharedPrototypeBean shared;
@PostConstruct public void init() {
System.out.println("FirstPrototypeBean.init() with shared " + shared);
}
}
@Component @Scope("prototype") static class SecondPrototypeBean {
@Autowired SharedPrototypeBean shared;
@PostConstruct public void init() {
System.out.println("SecondPrototypeBean.init() with shared " + shared);
}
}
@Component @Scope("prototype") static class MainPrototypeBean {
@Autowired FirstPrototypeBean first;
@Autowired SecondPrototypeBean second;
}
}
Und die Ausgabe der Ausführung ist:
FirstPrototypeBean.init() with shared [email protected]
SecondPrototypeBean.init() with shared [email protected]
Prototyp Bohnen haben unterschiedliche Instanzen für jede Injektion, die der Behälter herstellt. Ich würde argumentieren, dass 'SharedPrototypeBean 'tatsächlich keine prototypische Bean ist, sondern ein' @Scope (" singleton ")'. –
@ M.Prokhorov aber würde das nicht dasselbe bedeuten 'SharedPrototypeBean' würde für alle 'MainPrototypeBean'-Instanzen verwendet werden, was die Anforderung entschärft? – Mena
Hinweis: Ich vermute, dass die Verwendung eines Bereichs-Proxys hier helfen könnte. – Mena