In Spring, scope refers to the lifecycle of a bean, which determines how many instances of the bean will be created and when. There are several scopes available in Spring, including singleton and prototype.
Singleton Scope: In singleton scope, only one instance of the bean is created per Spring container, and this instance is shared across all requests for the bean. This means that every time a bean is requested, the same instance is returned. This can be useful for stateless beans that do not maintain any internal state between requests. Here’s an example of how to define a singleton bean in Spring:
@Service
@Scope("singleton")
public class MyService {
// bean implementation
}
Prototype Scope: In prototype scope, a new instance of the bean is created every time it is requested. This means that the instance is not shared across requests, and any state that is maintained by the bean is reset every time a new instance is created. This can be useful for stateful beans that maintain internal state between requests. Here’s an example of how to define a prototype bean in Spring:
@Service
@Scope("prototype")
public class MyService {
// bean implementation
}
In summary, the main difference between singleton and prototype scope in Spring is that singleton scope creates only one instance of a bean and shares it across all requests, while prototype scope creates a new instance of the bean for each request. The choice of scope depends on the specific requirements and constraints of the application.