Junior — Middle
Explain the concept of the Prototype scope in the context of Spring managed beans?
sobes.tech AI
Answer from AI
In Spring, the scope Prototype means that each request for a bean creates a new instance of that bean.
Unlike Singleton, where one instance is used throughout the application, Prototype creates a new object on each request. This is useful when the bean contains state that should not be shared between different clients or threads.
Example:
@Component
@Scope("prototype")
public class MyPrototypeBean {
// fields and methods
}
When such a bean is injected into a Singleton, Spring will create one instance of Prototype at initialization, not on each request. To handle this, ObjectFactory or Provider can be used.
Thus, Prototype scope ensures a new bean instance is created on each request to the Spring container.