2

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);
 }
}
omerstack
  • 535
  • 9
  • 23
  • *I found the prototype bean to do that*: well, as you see, it doesn't do that. If you want the same instance to always be returned when callin getBean(), it should be a singleton, not a prototype. Prototype precisely means: create a new instance every time. – JB Nizet Jul 06 '19 at 13:41
  • Sir, you didn't read my question well. My request is sometimes to create a new instance and sometimes to retrieve the instance that I previously created. So singleton is useless. It always returns the same instance to me. – omerstack Jul 06 '19 at 13:47
  • Sir, you never wrote anything like that in your question. Read it again. You also talk about bean names, but your code doesn't use any name anywhere, making it quite confusing. But anyway, even if that was possible, how could Spring know when to return an existing instance (and which one), and when to create a new one. – JB Nizet Jul 06 '19 at 13:51
  • "I want to create a bean with a unique name that I have given at any time. If a bean has already been created under this name, I want to bring the old bean." I tried to explain here. I think Spring can bring it back when I call it back with a unique name.I don't know how to write this in code. So my example may be ridiculous. I'il fix it now. – omerstack Jul 06 '19 at 13:59
  • 2
    Spring won't do that for you. It only creates beans that it knows about. Not dynamically based on new, unknown names. What you need is a cache (i.e some kind of Map). – JB Nizet Jul 06 '19 at 14:01

0 Answers0