Hi. I'm using Spring Webflux and have controllers ...
# spring
d
Hi. I'm using Spring Webflux and have controllers with suspending functions. I'd like to have all of those controller functions invoked with a coroutine that has an element within the coroutine context. The best I can think of so far is to manually add the context element as
withContext
inside each and every controller function - something like this:
Copy code
@GetMapping("/foo")
    suspend fun getFoo(): Foo {
        withContext(SomeCoroutineContextElement()) {
            TODO("Do something")
        }
    }
Is there a better way - i.e. a way to add the context across all controller functions, so I don't need to litter every one of them with
withContext
?
t
I'd be interested in this as well. We use the MDC to pass along a correlation id in most of our apps, and doing it with suspend functions would require the same thing you are talking about here. Very interested in a way around that.
b
I'm not sure with annotated controllers but with the functional style you can do it in a filter.
Copy code
filter { request, next -> withContext() { next(request) } }
d
🤔 I wonder if we can mix functional filter and annotated controller as the handler. Shouldn't be hard to test...
b
I wasn't able to find a way to do it.
d
Yep I wasn’t able to either. Thanks for the tip around the functional filters though. 👍