새소식

반응형
Java/Spring

RequestContextHolder

  • -
반응형

RequestContextHolder 클래스란?

Spring MVC 에서 현재 HTTP 요청(request) 과 관련된 컨텍스트 정보를 Thead Local 방식으로 관리해주는

유틸리티 클래스이다.

즉, 현재 처리중인 요청의 HttpServletRequest 나 HttpSession 에 접근할 수 있게 도와주는 도구입니다.

 

📌 주요 목적

Spring 에서는 HTTP 요청이 하나의 스레드에서 처리되므로, RequestContextHolder 를 통해 전역 어디에서든

요청 정보에 접근할 수 있습니다.

 

🔍 currentRequestAttributes() 메서드

RequestAttributes attrs = RequestContextHolder.currentRequestAttributes();

 

  • 현재 스레드에 바인딩된 요청 속성(RequestAttributes) 를 반환합니다.
  • 반환된 객체는 일반적으로 ServletRequestAttributes 로 캐스팅할 수 있다.
  • 내부적으로 ThreadLocal 에 저장된 요청 정보를 가져오는 것이므로, 컨트롤러, 서비스 등에서 현재 요청에 접근할 필요가 있을때 유용합니다.

✨ 사용 예시

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attr.getRequest();
HttpSession session = request.getSession();

이런 식으로 현재 요청의 request, session 등을 가져올 수 있습니다.

 

💡 자주 사용하는 메서드들

메서드 설명
getRequestAttributes() 현재 요청 속성이 있을 경우 반환하고, 없으면 null 반환
currentRequestAttributes() 현재 요청 속성이 없으면 IllegalStateException 발생
setRequestAttributes(RequestAttributes attributes) 수동으로 요청 속성을 설정함 (테스트용도나 비웹 환경에서 유용)
resetRequestAttributes() 요청 속성 초기화
initRequestAttributes(RequestAttributes attributes) setRequestAttributes()와 유사하나 중복 방지

 

✅ 언제 사용하는가?

  • 서블릿 요청이 아닌 곳에서 요청 객체가 필요할 때
    • 예: AOP, 비동기 로직, Interceptor 외부
  • 로깅/트래킹
    • 예: 현재 요청의 IP, 헤더 정보를 서비스나 로그에서 활용할 때
  • 세션 기반 사용자 정보 접근
    • 예: HttpSession 에서 사용자 ID, 역할 등을 가져올 때

⚠️ 주의할 점

  • RequestContextHolder 는 HTTP 요청 스레드 내에서만 작동한다.
    • 다른 스레드에서 사용할 경우 별도로 setRequestAttributes() 로 설정해야 한다.
  • WebFlux 같은 리액티브 환경에서는 사용 불가하며, MVC 전용이다.

 

📚 결론

특징 설명
용도 현재 요청에 대한 정보 접근 (request, session 등)
환경 Spring MVC (서블릿 기반) 에서만 사용
핵심 메서드 currentRequestAttributes(), getRequestAttributes(), setRequestAttributes()
주 사용처 AOP, 로깅, 세션 접근 등

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형
Contents