23

In the classic spring-mvc it is possible to set request scoped attributes on a RequestContextHolder. Building on that, we can parse an incoming request in a HandlerInterceptorAdapter, set request parameters such as currently logged in user, unique request ID (for log correlation) and so on. These request attributes can be retrieved statically from any service (not only controllers) during the request's lifetime.

I am trying to achieve something similar with spring-webflux.

I could use a WebFilter to intercept all incoming requests, get the current ServerWebExchange and set attributes on it. However I don't see any way to get the current request's ServerWebExchange anywhere else other than controller methods.

I am looking for a better solution than passing ServerWebExchange (or ServerHttpRequest) all around.

It seems like this is difficult to achieve in webflux since we cannot rely on saving variables associated with a particular request on ThreadLocal (because of the non-blocking architecture, a single thread can switch between requests mid-flight).
Still, this is an important requirement. Maybe there is a different approach?

Doron Gold
  • 3,664
  • 4
  • 32
  • 44
  • 1
    It's been almost 3 years. Has there been any update on this? – Andrew T Finnell May 07 '20 at 20:15
  • 1
    @AndrewTFinnell see this issue that I had opened at the time: https://github.com/spring-projects/spring-framework/issues/20239. I have stopped following this issue because my team has moved from Spring-webflux back to Spring-MVC, but it looks like there has been some progress. – Doron Gold May 09 '20 at 09:26
  • @DoronGold why did you move back to MVC? – Cristian Rodriguez Oct 03 '21 at 17:55

1 Answers1

6

The approaches you're describing are the ones currently supported. As you've underlined, using a static approach with ThreadLocals is not possible.

Reactor is looking into alternatives with a new context feature (see this PR). Spring is likely to pick that up and use it, but not necessarily for request attributes since the current model fits quite well.

If you'd like a particular extension point to intercept requests, please create a JIRA issue on the Spring Framework project, describing what you're trying to achieve and where things are failing.

Brian Clozel
  • 56,583
  • 15
  • 167
  • 176
  • 1
    You might want to look for inspiration in HATEOAS library - https://github.com/spring-projects/spring-hateoas/blob/master/src/main/java/org/springframework/hateoas/server/reactive/HypermediaWebFilter.java and https://github.com/spring-projects/spring-hateoas/blob/master/src/main/java/org/springframework/hateoas/server/reactive/WebFluxLinkBuilder.java – Jan Mares May 13 '19 at 20:29