Prototype scope in Spring creates a new bean instance every time the bean is requested from the Spring IoC container. Unlike Singleton scope, where the same object is shared, Prototype scope ensures that each request receives a completely separate object.
Key Points: • A new bean instance is created for every request to the container. • Prototype beans are not shared across the application. • It is suitable for stateful objects that maintain request-specific data. • Spring manages bean creation but does not manage the complete lifecycle of prototype beans after initialization. • Prototype scope helps avoid issues that can occur when multiple users share the same object instance.
Example: A ReportGenerator bean that stores report-specific data should use Prototype scope so that each report request receives a fresh object.
Code Example:
@Component
@Scope("prototype")
public class ReportGenerator {
}Interview Tip: A concise interview answer is:
"In Prototype scope, Spring creates a new bean instance every time the bean is requested from the container. It is typically used for stateful components where each request requires an independent object."
Quick Comparison:
Singleton Scope: • One shared instance • Default scope • Suitable for stateless beans
Prototype Scope: • New instance per request • Suitable for stateful beans • No object sharing