When would you use singleton scope and when prototype scope in Spring?
Singleton and Prototype are two commonly used Spring bean scopes. The choice between them depends on whether the application requires a shared instance or a new instance for each request.
Key Points
Singleton scope creates only one bean instance per Spring container and shares it across the application.
Prototype scope creates a new bean instance every time it is requested from the container.
Singleton is suitable for stateless components that can be safely shared by multiple users.
Prototype is suitable for stateful objects where each usage requires a separate instance.
Singleton is the default bean scope in Spring.
Example
Singleton: Service classes, DAO classes, configuration classes, and utility components that are shared across the application.
Prototype: Shopping cart objects, report generators, or temporary data holders where each request requires a fresh object.
@Component
@Scope("singleton")
public class UserService {
}
@Component
@Scope("prototype")
public class ReportGenerator {
}
Interview Tip
A concise interview answer is
Use Singleton scope when a single shared instance is sufficient for the entire application, such as service or repository beans. Use Prototype scope when a new object is required for every request, especially for stateful components that should not be shared.