Member-only story
Understanding Bean Scopes in Spring Boot Applications

When building robust and scalable applications using the Spring Boot framework, developers often encounter the concept of “bean scopes.” In Spring Boot, beans are managed objects within the Inversion of Control (IoC) container, and their scope determines their lifecycle and visibility.
Choosing the appropriate scope depends on the nature of the bean and its intended usage within the application. For example, a service that manages application-wide state might be a singleton, while a form-backing object in a web application might be a prototype to avoid concurrency issues.
You can specify the scope of a bean using the @Scope
annotation in combination with ConfigurableBeanFactory.SCOPE_...
constants or directly using the scope name as a string. Let’s explore the various bean scopes available in Spring Boot and understand their use cases.
1. Singleton Scope
Definition:
- Only one instance of the bean is created for the entire application context.
Use Case:
- Ideal for stateless services or components that can be shared across the application.
- They are commonly used for services managing shared resources.
Annotation used as:
@Scope(value = “singleton”)
or
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
2. Prototype Scope:
Definition:
- A new instance is created each time the bean is requested.
Use Case:
- It is useful for stateful beans where each client or component should have its instance.
- They are used when you want to avoid a shared state between multiple clients.
Annotation used as:
@Scope(value = “prototype”)
or
@
Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
3. Request Scope:
Definition:
- A new instance is created for each HTTP request. Applicable in a web-based context.