Singleton and Prototype Scopes in the Spring Boot
- #Spring
- #Java
In Spring Boot (and the broader Spring Framework), Singleton and Prototype are two common bean scopes that determine the lifecycle and the number of instances of a Spring bean.
1. Singleton Scope: One Instance per Spring Container
The default scope. The Spring will create only one instance of that bean for the entire application context. Every time the bean is requested, the same instance is returned.
This is useful for beans that don't maintain state between requests or need a shared, global state across the entire application.
@Component
public class MySingletonBean {
public MySingletonBean() {
System.out.println("MySingletonBean instance created!");
}
}
Spring will create a single instance of MySingletonBean and reuse it throughout the application.
2. Prototype Scope: New Instance per Request
In contrast to Singleton, a prototype bean results in a new instance each time it's requested.
This is useful for beans that need to maintain state specific to a particular operation or request. For example, objects that need to be created on the fly and shouldn't share state with others.
@Component
@Scope("prototype")
public class MyPrototypeBean {
public MyPrototypeBean() {
System.out.println("MyPrototypeBean instance created!");
}
}
Practical Example:
Imagine you have a DatabaseConnection class. If your application requires only one database connection that’s shared throughout the application, a singleton scope would be ideal. But if your application needs a new connection every time a user interacts with the system (i.e., each request requires a separate connection), you would use the prototype scope.