Understanding Bean Scopes in Spring Boot

java dev.to

Understanding Bean Scopes in Spring Boot

Spring Boot is one of the most widely used frameworks for building Java applications because it simplifies configuration, reduces boilerplate code, and helps developers create production-ready applications faster. Among the many important concepts in Spring Boot, Bean Scope plays a major role in understanding how Spring manages objects inside the application.

Bean scope tells us how many instances of a bean Spring creates, when those instances are created, and how long they remain active in the Spring container. This concept is very important because different parts of an application need different lifecycles. Some objects should be shared across the whole application, while others should be created separately for each request or each user session.

If you understand bean scopes clearly, you can design your Spring Boot application in a better way, improve performance, and avoid unnecessary memory usage.

What is a Bean?

In Spring Boot, a bean is simply an object that is created, managed, and controlled by the Spring IoC (Inversion of Control) container. Instead of creating objects manually using the new keyword, Spring creates them for us and injects them wherever they are needed.

For example, if you have a service class, repository class, or controller class, Spring can automatically create an instance of that class and manage its lifecycle. This makes the application easier to maintain and test.

A bean goes through several stages in its lifecycle:

=> Spring creates the bean instance
=> Spring injects dependencies into it
=> Spring initializes it
=> Spring uses it in the application
=> Spring destroys it when it is no longer needed

The scope of the bean decides how this lifecycle behaves.

Types of Bean Scopes in Spring Boot

Spring Boot supports different bean scopes depending on the type of application and the requirement of the object. The most commonly used scopes are Singleton, Prototype, Request, Session, and Application.

1. Singleton Scope

Singleton is the default scope in Spring Boot. This means that only one instance of the bean is created for the entire Spring container. Whenever the bean is requested, Spring returns the same object again and again.

This is the most commonly used scope because many beans in an application do not need multiple instances. For example, service classes and repository classes usually contain business logic or database access logic, and they can safely be shared across the application.

How it works:

Spring creates the bean only once when the container starts or when it is first needed.
The same bean instance is shared by all requests and all users.
This helps save memory and improves performance.

Use Case:
Service classes, repositories, helper classes, and utility classes.

Example:
If you have a UserService bean with singleton scope, every controller or component that uses UserService will receive the same object instance.

2. Prototype Scope

In Prototype scope, Spring creates a new bean instance every time the bean is requested from the container. This means that each request for the bean gives a fresh object.

This scope is useful when you need a separate object for each use, especially when the object contains temporary or user-specific data. Unlike singleton beans, prototype beans are not shared.

How it works:

Spring creates a new instance whenever the bean is requested.
Each caller gets a different object.
Spring does not fully manage the bean after creation in the same way it does for singleton beans.

Use Case:
Objects that maintain temporary state, user-specific data, or objects that should not be shared between different parts of the application.

Important Note:
Prototype beans are created by Spring, but Spring does not manage their complete lifecycle after creation. This means destruction callbacks are not automatically called in the same way as singleton beans.

3. Request Scope

Request scope is used in web applications. In this scope, Spring creates a new bean instance for every HTTP request. Once the request is completed and the response is sent back to the client, the bean is destroyed.

This scope is very useful when you want to store data that is only needed during a single request. For example, if a controller or service needs to keep track of request-specific information, request scope is a good choice.

How it works:

A new bean is created when an HTTP request starts.
The same bean is used throughout that request.
After the request finishes, the bean is removed.

Use Case:
Handling request-specific data such as request IDs, form data, or temporary processing information in web applications.

4. Session Scope

Session scope creates one bean instance per user session. The bean remains available as long as the user session is active. When the session expires or is invalidated, the bean is destroyed.

This scope is useful when you want to store information related to a particular user during their interaction with the application. Since each user has a separate session, each user gets a separate bean instance.

How it works:

When a user starts a session, Spring creates a bean for that session.
The same bean is reused for all requests made by that user during the session.
When the session ends, the bean is removed.

Use Case:
Storing user login information, shopping cart details, preferences, or any session-based data.

Example:
If one user adds items to a shopping cart, those items can be stored in a session-scoped bean so that the cart remains available until the session ends.

5. Application Scope

Application scope creates one bean instance for the entire web application. This bean is shared across all users, all sessions, and all requests within the application.

This scope is similar to singleton in many cases, but it is specifically tied to the web application context. It is useful when you want to store data that should be available globally throughout the application.

How it works:

Spring creates one bean for the whole application.
All users and sessions share the same bean.
The bean remains active as long as the application is running.

Use Case:
Application-wide configuration, shared resources, global counters, or common data that must be accessible to everyone.

Why Are Bean Scopes Important?

Bean scopes are important because they help developers control the lifecycle of objects in a Spring Boot application. Not every object should live for the same amount of time. Some objects should be shared, while others should be created separately for each request or session.

Using the correct scope provides several benefits:

1.Better memory management:
Spring creates only the number of objects that are actually needed.
2.Improved performance:
Reusing singleton beans reduces object creation overhead.
3.Proper data isolation:
Request and session scopes help keep user-specific data separate.
4.Cleaner application design:
Developers can choose the right lifecycle for each bean based on its purpose.
5.Reduced bugs:
Using the wrong scope can cause unexpected behavior, especially when dealing with shared mutable data.

For example, if you use a singleton bean to store user-specific data, different users may accidentally share the same data, which can lead to serious problems. On the other hand, if you use prototype or session scope correctly, each user or request gets its own separate object.

Source: dev.to

arrow_back Back to Tutorials