I want to create a bean with a unique name that I have given at any time. I also want to create a new instance with this unique name every time I call it. I just want to reach the old instance of a bean with that unique name is created in some cases. If a bean has already been created under this name, I want to bring the old bean. I found the prototype bean to do that. But every time I call bean, it creates a new instance.And I couldn't find the old bean back.
Example :
public class MyPrototypeBean {
private String dateTimeString = LocalDateTime.now().toString();
public void showMessage(){
System.out.println("Hi, the time is "+ dateTimeString);
}
}
@Configuration
public class AppConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MyPrototypeBean prototypeBean() {
return new MyPrototypeBean();
}
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
MyPrototypeBean bean4 = context.getBean(MyPrototypeBean.class);
bean4.showMessage();
Thread.sleep(1000);
MyPrototypeBean bean5 = context.getBean(MyPrototypeBean.class);
bean5.showMessage();
Thread.sleep(1000);
MyPrototypeBean bean6 = context.getBean(MyPrototypeBean.class);
bean6.showMessage();
Thread.sleep(1000);
}
}