Junior — Middle
What does defining the scope for beans with singleton and prototype values in Spring mean, and how does it affect their behavior?
sobes.tech AI
Answer from AI
In Spring, the scope of a bean defines its lifecycle and visibility.
-
singleton — this is the default scope. Whenever a bean with this scope is requested, Spring returns the same instance throughout the container's lifecycle. This means the bean is created once and reused.
-
prototype — a new instance is created each time the bean is requested. Spring does not manage the lifecycle of such beans after creation, so each call to
getBeanreturns a new object.
Impact on behavior:
- Singleton beans save resources and maintain a shared state for all users.
- Prototype beans are useful when a new instance with independent state is needed for each use.
Example:
@Component
@Scope("prototype")
public class MyPrototypeBean {
// each call to getBean creates a new object
}
@Component
@Scope("singleton")
public class MySingletonBean {
// one object for the entire container
}
Thus, the choice of scope affects how and when objects are created and how long they live in the application.