Middle
Čo sa stane, ak sa pokúsite získať ten istý bean v ApplicationContext?
sobes.tech AI
Odpoveď od AI
ApplicationContext bude predvolene vrátiť odkaz na ten istý bean, pretože rozsah beanov v Spring je predvolene singleton.
V prípade, že je bean nakonfigurovaný s iným rozsahom, napríklad prototype, tak pri každom požiadavke ApplicationContext vytvorí a vráti nový exemplár beana.
Príklad konfigurácie beana s rozsahom prototype:
@Configuration
public class AppConfig {
@Bean
@Scope("prototype") // Určujeme rozsah `prototype`
public MyPrototypeBean myPrototypeBean() {
return new MyPrototypeBean();
}
}
Príklad získania beana z ApplicationContext:
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyPrototypeBean bean1 = context.getBean(MyPrototypeBean.class);
MyPrototypeBean bean2 = context.getBean(MyPrototypeBean.class);
System.out.println(bean1 == bean2); // Pre singleton vráti true, pre prototype false
context.close();
}
}