Junior — Middle
Can you explain the concept of Scope in the context of Spring and its role in bean lifecycle management?
sobes.tech AI
Answer from AI
In Spring, scope defines the lifecycle and visibility of a bean — that is, how long and in what context the object will exist.
Main types of scope:
- singleton (default): one instance of the bean is created for the entire Spring container and is reused.
- prototype: each request for a bean creates a new instance.
- request: the bean lives within a single HTTP request (for web applications).
- session: the bean lives within an HTTP session.
- application: the bean lives within the ServletContext.
The role of scope is to manage the creation and lifetime of objects, which is important for resource optimization and correct application behavior. For example, singleton is suitable for stateless services, while prototype is for stateful objects that should not be shared.