Similar to Is there a static way to get the current HttpServletRequest in Spring, I want to get ServerHttpRequest in my spring webflux project via a static method, so i don't need to pass it across multiple layers all the way from controller. What's the best way to achieve this ?
1 Answer
Below is the static way to get the context for the current request:
Note: If getServerHttpRequest() is blocked, then only the keys which have been set by that point will be available.
public static Mono<ServerHttpRequest> getServerHttpRequest() { return Mono.deferContextual(Mono::just) .map(contextView -> contextView.get(ServerWebExchange.class).getRequest()); } Also, it could be achieved via :
mono.subscriberContext // deprecated And recently, Springflux has introduced "transformDeferredContextual" which is a more cleaner approach:
mono.transformDeferredContextual( (orginialMono, context ) -> { ... do something return orginialMono; // later this will be flatmapped });
ServerWebExchangeshould be available in the subscriber context.staticaccess relies on threadlocals - which for obvious reasons don’t work with reactive; at least not without significant problems.