Junior — Middle
What is the difference between Singleton and Prototype scopes in the Spring Framework?
sobes.tech AI
Answer from AI
In the Spring Framework, scopes define the lifecycle and visibility of beans.
-
Singleton — this is the default scope. In this case, Spring creates a single instance of the bean for the entire Spring container. All requests to this bean receive the same object. This saves resources and is convenient for services that do not store state.
-
Prototype — with this scope, Spring creates a new instance of the bean each time it is requested from the container. This is useful when a separate object with its own state is needed for each use.
Example:
@Component
@Scope("prototype")
public class MyPrototypeBean {
// each call to getBean() will create a new object
}
@Component
public class MySingletonBean {
// default is singleton
}
Thus, Singleton is one object per application, Prototype is a new object for each request.