Junior — Middle
In what cases should the specific Scope mechanism be used in the Spring Framework?
sobes.tech AI
Answer from AI
In the Spring Framework, the Scope mechanism defines the lifecycle and scope of a bean. The specific Scope to use depends on the requirements for the bean's lifetime and the context of its use:
- singleton (default): one instance for the entire Spring container. Used for services and components that should be shared.
- prototype: a new instance is created each time the bean is requested. Suitable for states that should not be shared.
- request (for web applications): the bean lives for a single HTTP request.
- session: the bean lives for the user's HTTP session.
- application: the bean lives for the entire lifecycle of the web application.
Example of using scope:
@Component
@Scope("prototype")
public class Task {
// each call to getBean(Task.class) will create a new instance
}
The choice of scope depends on how long the bean should exist and in what context it is used.