Loading

Quipoin Menu

Learn • Practice • Grow

spring / Spring Bean Scopes
interview

Q1. What are the different bean scopes in Spring?
Spring provides several scopes: singleton (one instance per container), prototype (new instance each time), request (one instance per HTTP request, web-aware), session (one per HTTP session), application (one per ServletContext), and websocket (one per websocket). For custom scopes, you can implement Scope interface.

Q2. What is the default scope in Spring?
The default scope is singleton. It means the Spring container creates only one instance of the bean per container, and that single instance is shared for all requests for that bean. This is memory-efficient and suitable for stateless beans.

Q3. When would you use prototype scope?
Prototype scope is used when you need a new instance of the bean each time it is requested. This is useful for stateful beans where each client needs its own instance, such as a shopping cart or a non-thread-safe object. Spring does not manage the complete lifecycle of prototype beans (destroy methods not called).

Q4. How do you define a bean with a specific scope using annotations?
Use the @Scope annotation on the bean definition. Example:
@Component @Scope("prototype") public class MyPrototypeBean { ... }
For web scopes, you can use @RequestScope, @SessionScope, etc.

Q5. What is the difference between singleton and prototype scopes?
Singleton scope returns the same instance for every request, while prototype returns a new instance each time. Singleton beans are created at container startup (by default), while prototype beans are created only when requested. Spring manages the full lifecycle of singleton beans but only instantiation and injection for prototype beans.