Junior — Middle
What is the role of the scope in the context of managing the lifecycle of a Bean?
sobes.tech AI
Answer from AI
Scope of a Bean defines the lifetime and visibility of the object instance within a dependency management container (e.g., Spring). It affects when the Bean is created, how many instances exist, and how long they live.
Main scope types:
- Singleton (default) — one instance of the Bean for the entire container, created at startup and lives until the application terminates.
- Prototype — a new instance is created each time the Bean is requested.
- Request (in web applications) — the Bean lives for the duration of a single HTTP request.
- Session — the Bean lives for the duration of a user session.
The role of scope is to manage the Bean's lifecycle, optimize resource usage, and ensure correct application behavior. For example, Singleton is suitable for stateful services, while Prototype is suitable for short-lived objects.
Example in Spring:
@Component
@Scope("prototype")
public class MyBean {
// each call to getBean() will create a new instance
}