DevOps.dev

Devops.dev is a community of DevOps enthusiasts sharing insight, stories, and the latest development in the field.

Follow publication

Member-only story

Understanding Bean Scopes in Spring Boot Applications

Saurav Kumar
DevOps.dev
Published in
3 min readJan 2, 2024

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in DevOps.dev

Devops.dev is a community of DevOps enthusiasts sharing insight, stories, and the latest development in the field.

Written by Saurav Kumar

Experienced Software Engineer adept in Java, Spring Boot, Microservices, Kafka & Azure.

No responses yet

Write a response