DEV Community

Sandeep Yadav
Sandeep Yadav

Posted on

How Does Session Scope Actually Work in Spring?

The Spring Framework provides several bean scopes that determine the lifecycle and visibility of beans in the application context:

  1. Singleton
  2. Prototype
  3. Request
  4. Session
  5. Application
  6. WebSocket

The last four scopes (request, session, application, and WebSocket) are specifically designed for web applications.

A session-scoped bean in Spring is a bean that is created once per HTTP session and shared across multiple requests from the same user. It remains active until the session expires or is invalidated.

Session-scoped beans are useful for storing temporary, user-specific data.

1. User ID : If a user ID is used across multiple HTTP requests, it's better to store it in the session scoped bean rather than querying the database on every request.
2. theme : If the application supports multiple UI themes, the userโ€™s theme preference can be stored in a session-scoped bean to maintain consistency across all requests.
3. User Roles : Once authenticated, the user's roles can be stored in a session-scoped bean for quick access during subsequent requests.
4. language : User's language preferences (locale) can be stored in a session-scoped bean to maintain a consistent user experience across all requests.

Lifecycle

  1. Created when a new HTTP session starts (e.g., user logs in).
  2. Destroyed when the session expires (timeout, logout, or invalidation).
  3. Each user gets their own instance.

Use Cases

  1. Storing user-specific data (e.g., shopping cart, authentication details).
  2. Maintaining state across multiple requests (e.g., user preferences).
  3. Avoiding repeated database fetches for session-related data.

I noticed many beginners struggle with @SessionScope in Spring. After researching, I made:

For spring and Java tutorials, you can join my youtube channel - https://youtube.com/@javalearnerss

Top comments (0)