Issue
I am writing a Spring Boot service and wanted to include some form of RequestContext
available to the controllers that might store things like the authenticated user and a request id. However, I see multiple approaches:
- Use an
@RequestScope
bean - Use
ServletRequest.setAttribute
- Use Spring
RequestContextHolder
What are the tradeoffs between these approaches?
Solution
Broadly speaking, RequestScope
is the Spring magic way. It internally uses a RequestContextHolder
which in turn depends on ServletRequest.setAttribute
.
Said differently, the Spring way, is IMHO RequestScope
. RequestContextHolder
makes sense if you prefer limit the magic of Spring annotations.
Finaly, ServletRequest.setAttribute
is still lower level, and should mainly be used if you want the code to be compatible with a non Spring application.
Moreover, for the first two ways, Spring uses a thread scoped object to store a reference to the request context, which allows the programmer to access the beans even in methods that do not explicitely receive the Request object.
Answered By - Serge Ballesta