25

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?

3
  • 1
    It's been almost 3 years. Has there been any update on this? Commented May 7, 2020 at 20:15
  • 1
    @AndrewTFinnell see this issue that I had opened at the time: 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. Commented May 9, 2020 at 9:26
  • @DoronGold why did you move back to MVC? Commented Oct 3, 2021 at 17:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.