Sobes.tech
Middle+

How will a prototype bind behave within a singleton?

sobes.tech AI

Answer from AI

A bean with prototype scope injected into a singleton bean will be created once during the singleton's initialization and then used multiple times (the same instance) each time it is accessed from the singleton. Spring creates a prototype bean each time it is requested from the container. When injected into a singleton, the request occurs only during the singleton's creation.

To solve this problem and obtain a new instance of the prototype bean each time it is accessed, you can use the following approaches:

  1. Injecting ApplicationContext: Explicitly retrieve the bean from the context each time.

    // Getting a prototype bean from the context
    PrototypeBean prototypeBean = applicationContext.getBean(PrototypeBean.class);
    
  2. Injecting ObjectFactory<PrototypeBean> or Provider<PrototypeBean>: Spring will provide a proxy that, when calling getObject() (for ObjectFactory) or get() (for Provider), will request a new instance from the context.

    // Using ObjectFactory to get a new instance
    @Autowired
    private ObjectFactory<PrototypeBean> prototypeBeanFactory;
    
    // ...
    
    public void someMethod() {
        PrototypeBean prototypeBean = prototypeBeanFactory.getObject();
        // ... use the new prototypeBean instance
    }
    
  3. Using @Lookup annotation: Create an abstract getter in the singleton, marked with @Lookup. Spring will generate a subclass of the singleton that overrides this method to obtain a new prototype bean.

    // Using @Lookup
    @Lookup
    public abstract PrototypeBean getPrototypeBean();
    
    // ...
    
    public void someMethod() {
        PrototypeBean prototypeBean = getPrototypeBean();
        // ... use the new prototypeBean instance
    }