Bean scope in Spring defines the lifecycle and visibility of a bean within the Spring IoC container. It determines how many bean instances are created and how long those instances remain available.
Key Points: • Singleton: Only one instance of the bean is created per Spring container. This is the default scope. • Prototype: A new bean instance is created every time it is requested from the container. • Request: A separate bean instance is created for each HTTP request in a web application. • Session: A single bean instance is maintained for each user session. • Application: One bean instance is shared across the entire web application. • WebSocket: One bean instance is created for each WebSocket session.
Example: A UserService bean is typically configured as Singleton because it can be shared across the application. A ShoppingCart bean is often configured as Session scope because each user should have a separate cart.
Code Example:
@Component
@Scope("prototype")
public class UserBean {
}Interview Tip: A concise interview answer is:
"Spring provides several bean scopes, including Singleton, Prototype, Request, Session, Application, and WebSocket. Singleton is the default scope and creates one shared bean instance per Spring container, while other scopes create beans based on specific application contexts."