Junior — Middle
What is the difference between the scope of Singleton and Prototype in the context of dependency injection?
sobes.tech AI
Answer from AI
In the context of dependency injection, scope defines the lifecycle and the number of instances of created objects.
-
Singleton: the object is created once for the entire lifecycle of the application or DI container. All requests for this dependency receive the same instance. This is convenient for services that need to maintain state or be shared.
-
Prototype: a new instance of the object is created with each request. This is useful when an independent object with its own state is required.
Example:
// Singleton scope
@Component
@Scope("singleton")
public class MyService {
// one instance for the application
}
// Prototype scope
@Component
@Scope("prototype")
public class MyPrototypeService {
// a new instance with each request
}
Thus, Singleton provides a single instance, while Prototype provides multiple independent instances, affecting state management and application performance.