Sobes.tech
Junior — Middle

What methods can be used to obtain a new instance of a component configured with the prototype pattern in Spring or similar frameworks?

sobes.tech AI

Answer from AI

In Spring, to obtain a new instance of a component with the prototype scope, several approaches are used:

  1. @Scope("prototype") annotation — when declaring a bean with this scope, Spring creates a new object on each request from the context.

  2. ApplicationContext.getBean() — each call to this method for a prototype bean returns a new instance.

  3. ObjectFactory or Provider — inject a factory into a singleton component that returns a new prototype object upon call:

@Component
@Scope("prototype")
public class MyPrototypeBean { }

@Component
public class SingletonBean {
    private final ObjectFactory<MyPrototypeBean> prototypeFactory;

    public SingletonBean(ObjectFactory<MyPrototypeBean> prototypeFactory) {
        this.prototypeFactory = prototypeFactory;
    }

    public void usePrototype() {
        MyPrototypeBean prototype = prototypeFactory.getObject();
        // use prototype
    }
}
  1. Lookup method injection — annotate a method in a singleton bean with @Lookup, and Spring will override it to return a new prototype instance.

Thus, the key point is that a prototype bean is created anew on each request from the context, and to access it from singleton components, factories or lookup injections are used.

What methods can be used to obtain a new instance of… - sobes.tech