<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sandeep Yadav</title>
    <description>The latest articles on DEV Community by Sandeep Yadav (@sandeep_yadav_e6573927c3c).</description>
    <link>https://dev.to/sandeep_yadav_e6573927c3c</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3111119%2Fbde54595-7cf6-4b91-9a15-5b5447151149.png</url>
      <title>DEV Community: Sandeep Yadav</title>
      <link>https://dev.to/sandeep_yadav_e6573927c3c</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sandeep_yadav_e6573927c3c"/>
    <language>en</language>
    <item>
      <title>Want to Learn About Request-Scoped Beans in Spring? 📺 Watch the video here: https://youtu.be/GYyKYB9-72Q #Spring #Java #WebDevelopment #RequestScope #Programming</title>
      <dc:creator>Sandeep Yadav</dc:creator>
      <pubDate>Thu, 01 May 2025 18:48:56 +0000</pubDate>
      <link>https://dev.to/sandeep_yadav_e6573927c3c/want-to-learn-about-request-scoped-beans-in-spring-watch-the-video-here-3dhj</link>
      <guid>https://dev.to/sandeep_yadav_e6573927c3c/want-to-learn-about-request-scoped-beans-in-spring-watch-the-video-here-3dhj</guid>
      <description></description>
    </item>
    <item>
      <title>How Does Request Scope Actually Work in Spring?</title>
      <dc:creator>Sandeep Yadav</dc:creator>
      <pubDate>Wed, 30 Apr 2025 20:13:22 +0000</pubDate>
      <link>https://dev.to/sandeep_yadav_e6573927c3c/how-does-request-scope-actually-work-in-spring-3le0</link>
      <guid>https://dev.to/sandeep_yadav_e6573927c3c/how-does-request-scope-actually-work-in-spring-3le0</guid>
      <description>&lt;p&gt;If you are not interested in theory, then I have uploaded video for request scope on youtube.&lt;br&gt;
URL : &lt;a href="https://youtu.be/GYyKYB9-72Q" rel="noopener noreferrer"&gt;https://youtu.be/GYyKYB9-72Q&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Spring Framework provides several bean scopes that determine the lifecycle and visibility of beans in the application context.&lt;/p&gt;

&lt;p&gt;The Scopes are :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Singleton&lt;/li&gt;
&lt;li&gt;Prototype&lt;/li&gt;
&lt;li&gt;Request&lt;/li&gt;
&lt;li&gt;Session&lt;/li&gt;
&lt;li&gt;Application&lt;/li&gt;
&lt;li&gt;WebSocket&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The last four scopes (request, session, application, and WebSocket) are specifically designed for web applications.&lt;/p&gt;

&lt;p&gt;I will explain the request scope in detail.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Spring, a request-scoped bean is a bean that is created once per HTTP request and destroyed when the request completes.&lt;/strong&gt;&lt;br&gt;
This means when the application receives an Http request:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It creates an instance of the request-scoped bean specifically for that request.&lt;/li&gt;
&lt;li&gt;The bean remains available throughout the request’s lifecycle.&lt;/li&gt;
&lt;li&gt;It gets automatically destroyed when the request processing completes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When a bean is defined request scoped bean then each HTTP request gets its own unique instance of the bean. It is useful for storing request-specific data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;To understand the request scope bean, I am going to an example of the ticket booking system.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fapgz8b1mhy51kggfsa5n.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fapgz8b1mhy51kggfsa5n.PNG" alt="Image description" width="800" height="497"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the diagram, you can see the components of a ticket booking system. The following are the components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Filter (JwtTokenFilter)&lt;/li&gt;
&lt;li&gt;Rest controller (Booking controller)&lt;/li&gt;
&lt;li&gt;Two services(BookingService and Notificationservice)&lt;/li&gt;
&lt;li&gt;Model class(UserContext) The fourth compoenent is user contrext bean. That would be injected into The jwt token filter, BookingService class and notification service.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;UserContext is a class that holds the current user’s information(user’s ID and name). It is declared a bean using @Component annotation and its scope is request. The UserContext bean is also injected into the BookingService and NotificationService.&lt;/p&gt;

&lt;p&gt;Flow :&lt;br&gt;
Step 1: The user sends a request to the Ticket Booking application. The filter first intercepts the request. The filter, JwtTokenFilter, validates the token, extracts the user ID and name from it, and stores them in the UserContext bean.&lt;/p&gt;

&lt;p&gt;Steps 2 : The request is received by the rest controller.&lt;/p&gt;

&lt;p&gt;Step 3: The rest controller uses the BookingService to book the ticket.&lt;/p&gt;

&lt;p&gt;Step 4: The rest controller then uses the NotificationService to send confirmation notification to user about the booking status.&lt;/p&gt;

&lt;p&gt;The scope of the UserContext bean is request, so the same UserContext bean is injected into BookingService and NotificationService classes.&lt;br&gt;
The current user’s information that is set into the request scoped bean UserContext in the filter will be available in the Booking service and Notification Service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Project structure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1v2heuiy8pvrta3nao1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1v2heuiy8pvrta3nao1.png" alt="Image description" width="800" height="501"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have created a Spring Boot project using Spring Boot version 3.2.4. The Java version is 21 (or 22, as Java 23 is not yet fully supported). I added five dependencies: the first two are Spring-related (spring-boot-starter-web and spring-boot-starter-security), and the last three are for JWT token handling (jjwt-api, jjwt-impl, and jjwt-jackson).&lt;/p&gt;

&lt;p&gt;This project follows a layered Spring Boot architecture with four main packages:&lt;br&gt;
controller — Contains REST API endpoints (e.g., UserController, AuthController).&lt;br&gt;
filter — Houses security filters (e.g., JWT validation filters like JwtAuthFilter).&lt;br&gt;
model — Includes entity/DTO classes (e.g., User, LoginRequest).&lt;br&gt;
service — Holds business logic (e.g., UserService, JwtService).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. UserContext class&lt;/strong&gt;&lt;br&gt;
In the model package, I’ve created a UserContext class.It is a request-scoped Spring bean that holds user-specific information (like userID and name) during HTTP request lifecycle. It is used in JWT-based authentication where JwtTokenFilter populates user details after token validation.&lt;/p&gt;

&lt;p&gt;`package com.learn.bean.scopes.model;&lt;/p&gt;

&lt;p&gt;import org.slf4j.Logger;&lt;br&gt;
import org.slf4j.LoggerFactory;&lt;br&gt;
import org.springframework.context.annotation.Scope;&lt;br&gt;
import org.springframework.context.annotation.ScopedProxyMode;&lt;br&gt;
import org.springframework.stereotype.Component;&lt;br&gt;
import org.springframework.web.context.WebApplicationContext;&lt;/p&gt;

&lt;p&gt;import java.util.UUID;&lt;/p&gt;

&lt;p&gt;@Component&lt;br&gt;
&lt;a class="mentioned-user" href="https://dev.to/scope"&gt;@scope&lt;/a&gt;(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)&lt;br&gt;
public class UserContext {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static Logger logger = LoggerFactory.getLogger(UserContext.class);

private String id;
private String userID;
private String name;

public UserContext() {
    this.id = UUID.randomUUID().toString();
    logger.info("UserContext bean is created, Bean ID : {}", id);
}

public void setUserID(String userID) {
    this.userID = userID;
}

public String getUserID() {
    return userID;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "UserContext{" +
            "Bean ID='" + id + '\'' +
            ", User ID='" + userID + '\'' +
            ", User Name='" + name + '\'' +
            '}';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/scope"&gt;@scope&lt;/a&gt;(value = WebApplicationContext.SCOPE_REQUEST): The class is also annotated with &lt;a class="mentioned-user" href="https://dev.to/scope"&gt;@scope&lt;/a&gt; annotation,it defines the lifecycle scope of a userContext bean. By setting attribute value = “request”, the bean becomes request-scoped, meaning:&lt;br&gt;
A new instance is created for each HTTP request.&lt;br&gt;
The instance is destroyed when the request completes.&lt;/p&gt;

&lt;p&gt;proxyMode = ScopedProxyMode.TARGET_CLASS: The second attribute in &lt;a class="mentioned-user" href="https://dev.to/scope"&gt;@scope&lt;/a&gt; is proxyMode and its value is target classs. It ensures that Spring creates a proxy to inject the request-scoped bean (UserContext) into singleton beans (e.g., controllers/services). At runtime, the proxy fetches the actual instance from the application context per HTTP request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. BookingService class&lt;/strong&gt;&lt;br&gt;
In the service package I have created a BookingService class. It is a Spring service (@Service) responsible for handling ticket booking logic. The request-scoped UserContext bean is injected into this service class.&lt;/p&gt;

&lt;p&gt;`package com.learn.bean.scopes.service;&lt;/p&gt;

&lt;p&gt;import com.learn.bean.scopes.model.UserContext;&lt;br&gt;
import org.slf4j.Logger;&lt;br&gt;
import org.slf4j.LoggerFactory;&lt;br&gt;
import org.springframework.beans.factory.annotation.Autowired;&lt;br&gt;
import org.springframework.stereotype.Service;&lt;/p&gt;

&lt;p&gt;@Service&lt;br&gt;
public class BookingService {&lt;br&gt;
    private static Logger logger = LoggerFactory.getLogger(BookingService.class);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired
private UserContext userContext;

public String bookTicket() {
    String eventId = "Ticket Booking";
    logger.info("User context object in booking service {}",userContext);
    // ticket booking logic goes here
    logger.info("Ticket booked for event: {}  by user: {} ",eventId, userContext.getName());
    return "Ticket booked successfully for user: " + userContext.getName();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;Business Method: bookTicket()&lt;br&gt;
In the bookTicket() method, I’ve added logging to track the UserContext object (logging beanId, userId, and name) for verification purposes. The method then proceeds with the ticket booking logic. Upon successful booking, the booking details are logged, and a confirmation message is returned.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. NotificationService class&lt;/strong&gt;&lt;br&gt;
In the service package I have created a NotificationService class. It is a Spring service (@Service) responsible for sending notifications (e.g., booking confirmations) to users. The request-scoped UserContext bean is injected in this class to send personalized notifications.&lt;/p&gt;

&lt;p&gt;`package com.learn.bean.scopes.service;&lt;br&gt;
import com.learn.bean.scopes.model.UserContext;&lt;br&gt;
import org.slf4j.Logger;&lt;br&gt;
import org.slf4j.LoggerFactory;&lt;br&gt;
import org.springframework.beans.factory.annotation.Autowired;&lt;br&gt;
import org.springframework.stereotype.Service;&lt;/p&gt;

&lt;p&gt;@Service&lt;br&gt;
public class NotificationService {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static Logger logger = LoggerFactory.getLogger(NotificationService.class);

@Autowired
private UserContext userContext;

public String sendConfirmation() {
    String eventId = "Ticket Booking";
    logger.info("User context object in notification service {}",userContext);
    // Send notification logic goes here
    logger.info("Confirmation sent to user: {} for event: {}",userContext.getName(), eventId);
    return "Ticket is booked for user: " + userContext.getName();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;sendConfirmationMethod(): In this method, I’ve added logging to track the UserContext object (including beanId, userId, and name) for verification. Next, we will implement the notification logic. Upon successfully sending the notification, the details are logged, and a confirmation message is returned.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. BookingController&lt;/strong&gt;&lt;br&gt;
In the controller package I have created a BookingController class.It is a Spring REST controller (@RestController) that handles HTTP requests related to ticket booking. It coordinates between the BookingService (for ticket processing) and NotificationService (for sending confirmations).&lt;/p&gt;

&lt;p&gt;The BookingService and NotificationService dependencies are injected in the controller.&lt;br&gt;
BookingService: Contains business logic for ticket booking.&lt;br&gt;
NotificationService: Handles sending confirmation messages (e.g., emails, SMS).&lt;/p&gt;

&lt;p&gt;It returns a confirmation message to the user after successful ticket booking.&lt;/p&gt;

&lt;p&gt;`package com.learn.bean.scopes.controller;&lt;/p&gt;

&lt;p&gt;import com.learn.bean.scopes.service.NotificationService;&lt;br&gt;
import com.learn.bean.scopes.service.BookingService;&lt;br&gt;
import org.springframework.beans.factory.annotation.Autowired;&lt;br&gt;
import org.springframework.http.ResponseEntity;&lt;br&gt;
import org.springframework.web.bind.annotation.GetMapping;&lt;br&gt;
import org.springframework.web.bind.annotation.RestController;&lt;/p&gt;

&lt;p&gt;@RestController&lt;br&gt;
public class BookingController {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired
private BookingService ticketBookingService;

@Autowired
private NotificationService notificationService;


@GetMapping("/bookTicket")
public ResponseEntity&amp;lt;String&amp;gt; bookTicket() {
    ticketBookingService.bookTicket();
    notificationService.sendConfirmation();
    return ResponseEntity.ok("Ticket booked successfully");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. JwtTokenFilter class&lt;/strong&gt;&lt;br&gt;
In the filter package, I have created a JwtTokenFilter class. It is a Spring component (@Component)that is responsible for JWT-based authentication. It intercepts incoming HTTP requests, validates JWT tokens, and populates user information into the UserContext.&lt;/p&gt;

&lt;p&gt;`package com.learn.bean.scopes.filter;&lt;/p&gt;

&lt;p&gt;import com.learn.bean.scopes.model.UserContext;&lt;br&gt;
import io.jsonwebtoken.Claims;&lt;br&gt;
import io.jsonwebtoken.JwtException;&lt;br&gt;
import io.jsonwebtoken.Jwts;&lt;br&gt;
import jakarta.servlet.FilterChain;&lt;br&gt;
import jakarta.servlet.ServletException;&lt;br&gt;
import jakarta.servlet.http.HttpServletRequest;&lt;br&gt;
import jakarta.servlet.http.HttpServletResponse;&lt;br&gt;
import org.slf4j.Logger;&lt;br&gt;
import org.slf4j.LoggerFactory;&lt;br&gt;
import org.springframework.beans.factory.annotation.Autowired;&lt;br&gt;
import org.springframework.beans.factory.annotation.Value;&lt;br&gt;
import org.springframework.stereotype.Component;&lt;br&gt;
import org.springframework.web.filter.OncePerRequestFilter;&lt;/p&gt;

&lt;p&gt;import java.io.IOException;&lt;br&gt;
import java.util.Date;&lt;/p&gt;

&lt;p&gt;@Component&lt;br&gt;
public class JwtTokenFilter extends OncePerRequestFilter {&lt;br&gt;
    private final Logger logger = LoggerFactory.getLogger(JwtTokenFilter.class);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired
private UserContext userContext;

@Value("${secret-key}")
private String secretKey;

public JwtTokenFilter() {
    logger.info("JwtTokenFilter bean is created");
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {
        String header = request.getHeader("Authorization");
        String token = (header != null &amp;amp;&amp;amp; header.startsWith("Bearer ")) ? header.substring(7) : null;
        if (token != null) {
            Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
            validateToken(claims);
            userContext.setUserID(claims.getSubject());
            userContext.setName((String) claims.get("name"));
            logger.info("userContext object is populated by JWtTokenFilter");
            logger.info("User context object in jwt token filter {}",userContext);
        }
        chain.doFilter(request, response);
    } catch (JwtException e) {
        logger.warn("JWT validation failed: {}", e.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
    }
}

private void validateToken(Claims claims) throws JwtException {
    if (claims.getExpiration().before(new Date())) {
        throw new JwtException("Token expired");
    }
    // userID validation code goes here
    // extract the userID and check the userID in DB, if userID is present,
    // it's a valid request, otherwise thrown Invalid user exception
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fexzz9ganuhf8y3dw4o0t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fexzz9ganuhf8y3dw4o0t.png" alt="Image description" width="800" height="538"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It gets the Authorization header from the request. If header is valid, it extracts the token by removing “Bearer “. If toke is present then it extracts the claims (payload) from the token using secret key. It validates the token by checking the expiration date. If taken ias valid then it populates the user details in User Context bean.Then the request proceeds to the next filter.&lt;/p&gt;

&lt;p&gt;If token validation fails (e.g., expired, tampered, or invalid), a 401 Unauthorized error is sent. The filter chain is not continued, blocking the request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Application properties&lt;/strong&gt;&lt;br&gt;
It contains a secret key, that is used by JwtFilter to extract the attributes from JWT token.&lt;/p&gt;

&lt;p&gt;`spring.application.name=request-scope&lt;/p&gt;

&lt;p&gt;secret-key=gDBp6ZZOuL/L4pJ0tkPjbJQfcgOyIt8g60e3UyciK78=`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. JwtTokenService&lt;/strong&gt;&lt;br&gt;
To generate JWT token for testing purpose, In the service package, I’ve implemented a JwtTokenService class that generates JWT tokens.&lt;/p&gt;

&lt;p&gt;The method generateSecretKey() generates a secret key and generateToken() method uses that secret key to generate the token.&lt;br&gt;
We need to add the secret key in the application.properties file. This secret key will be used by JwtToken filter to extract the claims from the token.&lt;/p&gt;

&lt;p&gt;`package com.learn.bean.scopes.service;&lt;/p&gt;

&lt;p&gt;import io.jsonwebtoken.Jwts;&lt;br&gt;
import io.jsonwebtoken.SignatureAlgorithm;&lt;br&gt;
import io.jsonwebtoken.io.Encoders;&lt;br&gt;
import io.jsonwebtoken.security.Keys;&lt;/p&gt;

&lt;p&gt;import java.security.Key;&lt;br&gt;
import java.util.Date;&lt;br&gt;
import java.util.HashMap;&lt;br&gt;
import java.util.Map;&lt;/p&gt;

&lt;p&gt;public class JwtTokenService {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    long duration = 1000 * 60 * 30; // 30 minutes in milliseconds
    String token = generateToken(duration, generateSecretKey());
    System.out.println("Token: " + token);
}

public static String generateToken(long duration, Key secretKey) {
    Map&amp;lt;String, Object&amp;gt; claims = new HashMap&amp;lt;&amp;gt;();
    claims.put("name", "Java Learnerss");  // Name
    claims.put("role", "USER");   // Custom claim

    return Jwts.builder()
            .setClaims(claims)
            .setSubject("javalearnerss")
            .setIssuedAt((new Date(System.currentTimeMillis())))
            .setExpiration(new Date(System.currentTimeMillis() + duration))
            .signWith(secretKey)
            .setHeaderParam("typ", "JWT")
            .compact();
}

public static Key generateSecretKey() {
    Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    // Display the security key
    byte[] keyBytes = secretKey.getEncoded();
    String base64Key = Encoders.BASE64.encode(keyBytes);
    System.out.println("Generated key: " + base64Key);
    return secretKey;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;Generate the secret key and token.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmvxm56pxo8gyvfwb2rl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmvxm56pxo8gyvfwb2rl.png" alt="Image description" width="800" height="470"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Copy this secret key and paste it into the application.properties file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run the application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0qt5t9tj0uttx3fqnl75.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0qt5t9tj0uttx3fqnl75.png" alt="Image description" width="800" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Send the request from postman.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2km9rl7mg6ghridihxfx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2km9rl7mg6ghridihxfx.png" alt="Image description" width="800" height="317"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the below screenshot, the app logs show that same UserContext bean is injected into JwtTokenFilter, BookingService and NotificationService classes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6w3gj9o7gd1wgg000ymg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6w3gj9o7gd1wgg000ymg.png" alt="Image description" width="800" height="205"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How Does Session Scope Actually Work in Spring?</title>
      <dc:creator>Sandeep Yadav</dc:creator>
      <pubDate>Wed, 30 Apr 2025 20:10:59 +0000</pubDate>
      <link>https://dev.to/sandeep_yadav_e6573927c3c/how-does-session-scope-actually-work-in-spring-4033</link>
      <guid>https://dev.to/sandeep_yadav_e6573927c3c/how-does-session-scope-actually-work-in-spring-4033</guid>
      <description>&lt;p&gt;The Spring Framework provides several bean scopes that determine the lifecycle and visibility of beans in the application context:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Singleton&lt;/li&gt;
&lt;li&gt;Prototype&lt;/li&gt;
&lt;li&gt;Request&lt;/li&gt;
&lt;li&gt;Session&lt;/li&gt;
&lt;li&gt;Application&lt;/li&gt;
&lt;li&gt;WebSocket&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The last four scopes (request, session, application, and WebSocket) are specifically designed for web applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;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.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Session-scoped beans are useful for storing temporary, user-specific data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. User ID&lt;/strong&gt; : 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.&lt;br&gt;
&lt;strong&gt;2. theme&lt;/strong&gt; : 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.&lt;br&gt;
&lt;strong&gt;3. User Roles&lt;/strong&gt; : Once authenticated, the user's roles can be stored in a session-scoped bean for quick access during subsequent requests.&lt;br&gt;
&lt;strong&gt;4. language&lt;/strong&gt; : User's language preferences (locale) can be stored in a session-scoped bean to maintain a consistent user experience across all requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lifecycle&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Created when a new HTTP session starts (e.g., user logs in).&lt;/li&gt;
&lt;li&gt;Destroyed when the session expires (timeout, logout, or invalidation).&lt;/li&gt;
&lt;li&gt;Each user gets their own instance.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Use Cases&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Storing user-specific data (e.g., shopping cart, authentication details).&lt;/li&gt;
&lt;li&gt;Maintaining state across multiple requests (e.g., user preferences).&lt;/li&gt;
&lt;li&gt;Avoiding repeated database fetches for session-related data.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I noticed many beginners struggle with &lt;code&gt;@SessionScope&lt;/code&gt; in Spring. After researching, I made:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A short video with real use case : &lt;a href="https://youtu.be/04nnFG2XKjQ" rel="noopener noreferrer"&gt;https://youtu.be/04nnFG2XKjQ&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;A GitHub repo with runnable code: &lt;a href="https://github.com/javalearnerss/bean-scopes/tree/main/session-scope" rel="noopener noreferrer"&gt;https://github.com/javalearnerss/bean-scopes/tree/main/session-scope&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For spring and Java tutorials, you can join my youtube channel - &lt;a href="https://youtube.com/@javalearnerss" rel="noopener noreferrer"&gt;https://youtube.com/@javalearnerss&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
