Spring WebFlux and Spring MVC in one project with implementing WebFilter as interceptor

531 Views Asked by At

I have an old Spring MVC application where I would like to introduce some new Reactive routes for async heavy processing. Normal MVC routes work fine like this and I can return a Mono or Flux.

@GetMapping("/{id}")
public Mono<String> doSomething(@PathVariable("id") Long id) {
    ...
}

I would like to get the request headers for further Context containing authentication information, and have this kind of filter in place so I could access the Request in Mono.deferContextual()

@Component
public class ReactiveRequestContextFilter implements WebFilter {
    public static final Class<ServerHttpRequest> SERVER_HTTP_REQUEST_CLASS = ServerHttpRequest.class;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        return chain.filter(exchange)
                    .contextWrite(ctx -> ctx.put(SERVER_HTTP_REQUEST_CLASS, request));
    }
}

However, the filter does not trigger with the default configuration. If add the configuration class

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer

I'm getting the following error

The Java/XML config for Spring MVC and Spring WebFlux cannot both be enabled, e.g. via @EnableWebMvc and @EnableWebFlux, in the same application.

Is there any way to access the request with this kind of pattern, when I would like to develop new functionality using Reactor/Mono, but can't refactor all the existing routes at once to support WebFlux entirely?

0

There are 0 best solutions below