Spring Boot
session management
common class
programming
Java

How can I get session from a common class in Spring Boot?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If a “common class” in Spring Boot needs access to session data, the best solution is usually not to fetch the session statically. Instead, inject the request or session through Spring-managed beans, or better yet, pass the specific values the class actually needs. That keeps the code testable and avoids turning session access into hidden global state.

The Straightforward Option: Inject HttpSession

If the class is Spring-managed and used within an HTTP request, you can inject HttpSession directly.

java
1import jakarta.servlet.http.HttpSession;
2import org.springframework.stereotype.Service;
3
4@Service
5public class SessionReader {
6    private final HttpSession session;
7
8    public SessionReader(HttpSession session) {
9        this.session = session;
10    }
11
12    public String getCurrentUser() {
13        return (String) session.getAttribute("currentUser");
14    }
15}

This works because Spring can proxy request-bound objects into normal beans when the context is correct.

Prefer Passing the Needed Value When Possible

Even though session injection works, many classes do not really need the entire session object. They need one value from it.

A cleaner controller-to-service flow is often:

java
1import jakarta.servlet.http.HttpSession;
2import org.springframework.web.bind.annotation.GetMapping;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class UserController {
7    private final AuditService auditService;
8
9    public UserController(AuditService auditService) {
10        this.auditService = auditService;
11    }
12
13    @GetMapping("/profile")
14    public String profile(HttpSession session) {
15        String user = (String) session.getAttribute("currentUser");
16        auditService.recordAccess(user);
17        return user;
18    }
19}

That design is easier to test because AuditService is no longer tied to the web layer.

Avoid Static Session Access Patterns

A common anti-pattern is trying to grab the session from a static utility or from code that Spring does not manage. That usually leads to fragile workarounds, hidden dependencies, and code that breaks outside web requests.

If the class is not a Spring bean, fix that first. Spring can only inject request and session state into objects it controls.

If You Really Need Request Context Access

As a fallback, Spring exposes request attributes through RequestContextHolder, but it should be treated as an escape hatch rather than a first choice.

java
1import jakarta.servlet.http.HttpServletRequest;
2import org.springframework.web.context.request.RequestContextHolder;
3import org.springframework.web.context.request.ServletRequestAttributes;
4
5public class SessionUtil {
6    public static String currentUser() {
7        ServletRequestAttributes attrs =
8                (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
9        HttpServletRequest request = attrs.getRequest();
10        return (String) request.getSession().getAttribute("currentUser");
11    }
12}

This works only inside an active request thread and is harder to mock than dependency injection.

Know When Session Access Is the Wrong Abstraction

If many common classes keep reaching into session state, the design often needs a dedicated user-context abstraction instead. That gives the application one place to interpret session-backed identity, locale, tenant, or preferences.

Then the rest of the code depends on CurrentUserContext or a similar interface, not on servlet APIs directly.

Keep Business Logic Session-Agnostic

The more your core services depend directly on servlet session APIs, the harder they become to test outside HTTP requests. A good boundary is to extract the user id, tenant id, or locale once near the web layer and pass those values downward.

That keeps the session as an input source rather than as a hidden dependency spread across the codebase.

Common Pitfalls

The biggest mistake is trying to access session state from a static helper or a non-Spring-managed object.

Another issue is injecting HttpSession everywhere when most code only needs one or two already-resolved values.

A third problem is using RequestContextHolder casually in deep business logic, which makes the code harder to test and more tightly coupled to the web layer.

Summary

  • If the class is Spring-managed, injecting HttpSession can work.
  • Passing the specific session-derived value is often cleaner than passing the whole session.
  • Avoid static session access patterns and non-managed utility code.
  • Use RequestContextHolder only as a fallback, not as the default design.
  • If session access spreads widely, introduce a dedicated user-context abstraction.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.