개발/Spring

[Spring] - RequestContextHolder

dongdev 2022. 6. 6. 18:50

RequestContextHolder는 Spring 컨텍스트에서 HttpServletRequest에 접근할 수 있게 도와준다.

따라서 이를 활용하면 HttpServletRequest를 사용하기 위해 request를 메소드 파라미터로 전달하지 않아도 된다.

 

RequestContextHolder 원리

  1. ThreadLocal을 사용해서 servlet이 호출되면 key,value (thread,HttpservletRequest)를 보관한다.
  2. 호출된 servlet과 동일한 thread내에서는 어느 곳에서든 같은 HttpServletRequest를 꺼내서 쓸수 있다.
  3. servlet이 종료 될 때 해당 thread를 key로 갖는 쌍을 제거한다.

 

RequestContextHolder 메소드

  • currentRequestAttributes()
  • getRequestAttributes()

HttpServletRequest를 가져오기 위해 위에 두 메소드를 사용하는데, 둘의 차이점은 getRequestAttributes()는 해당되는 RequestAttributes가 없으면 NULL을 반환한다.  currentRequestAttributes()는  해당되는 RequestAttributes가 없으면 예외를 발생시킨다.

 

테스트

@RestController
@Slf4j
public class TestController {

    @GetMapping("/requestTest")
    public String requestTest() {
        return "ok";
    }
}
@Aspect
@Service
@Slf4j
public class AspectJService {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void GetMapping() {}

    @Around("GetMapping()")
    public Object aroundg(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        log.info(request.getRequestURI());
        log.info(request.getParameter("name"));
        return joinPoint.proceed();
    }
}

간단하게 RequestContextHolder와 Aop를 활용하여 요청 URI와 파라미터를 로그로 찍어보자.

http://localhost:8080/requestTest?name=dongjun 호출 후, 콘솔창을 확인 해보면 아래와 같이 잘 찍히는 것을 볼 수 있다.