Middle
Ի՞նչ կլինի, եթե փորձեք ստանալ նույն բինը ApplicationContext-ում:
sobes.tech AI
Պատասխան AI-ից
ApplicationContext-ը ըստ նախնական կարգավորումների վերադարձնում է նույն բինի հղում, քանի որ Spring-ում բիների տեսանելիության ոլորտը նախնական կարգավորումների դեպքում singleton է:
Եթե բինը կոնֆիգուրացված է այլ ոլորտով, օրինակ prototype, ապա յուրաքանչյուր հարցում ApplicationContext-ը կստեղծի և կվերադարձնի բինի նոր օրինակ:
prototype ոլորտով բինի կոնֆիգուրացիայի օրինակ:
@Configuration
public class AppConfig {
@Bean
@Scope("prototype") // Նշում ենք `prototype` ոլորտը
public MyPrototypeBean myPrototypeBean() {
return new MyPrototypeBean();
}
}
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); // Singleton-ի դեպքում true, prototype-ի դեպքում false
context.close();
}
}