Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Your team mixes annotated controllers and router functions in one WebFlux service. How do you keep cross-cutting concerns (validation, error handling, security, documentation) consistent?

Each concern needs a mechanism that reaches both styles, or two mechanisms kept in step. @ControllerAdvice handlers apply only to annotated controllers, so router functions need filters (RouterFunction.filter) or onError in the builder, while a shared WebExceptionHandler or Boot's ErrorWebExceptionHandler can cover both. Security in a SecurityWebFilterChain already covers both because it is a web filter, functional handlers must call a Validator explicitly, and springdoc needs @RouterOperation annotations to document router functions. Above all, pick one style per service unless there is a clear reason to mix.

Why this question is asked

A service that started with annotated controllers often gains a few router functions later, perhaps copied from a gateway project or added for a streaming endpoint. Everything works until a client notices that errors look different depending on the endpoint, or a security review finds that the new routes were never documented. Interviewers ask this design question to see whether we know which Spring mechanisms apply to which handler type, and how we keep behaviour consistent. In this answer, we will recap how requests reach each style, then go concern by concern through error handling, validation, security and documentation, and finish with when mixing is justified.

1A Quick Recap: Two Handler Types Behind One Dispatcher

In WebFlux, every request passes through the WebFilter chain and then reaches DispatcherHandler. DispatcherHandler asks its handler mappings who can handle the request. RouterFunctionMapping returns a handler function from our routers; RequestMappingHandlerMapping returns an annotated controller method. Each kind is then invoked by its own adapter.

That structure tells us where each mechanism works. Anything at the WebFilter level, or at the WebExceptionHandler level after the dispatcher, sees both styles. Anything tied to the annotated adapter, such as @ControllerAdvice, @ExceptionHandler, @Valid argument resolution and @InitBinder, sees only annotated controllers.

Step throughWhere cross-cutting concerns apply
  1. WebFilter chainSpring Security, tracing, logging: both styles
  2. DispatcherHandlerfinds a handler from either mapping
  3. Router functionsRouterFunction.filter, onError, explicit Validator
  4. Annotated controllers@ControllerAdvice, @Valid, @ExceptionHandler
  5. WebExceptionHandler / ErrorWebExceptionHandlerlast resort for errors from both styles

5 layers, from the top down. Step through them one at a time.

Put a concern as high as it can go, so both styles share one implementation.

2Consistent Error Handling

The goal is one error format, ideally ProblemDetail (RFC 9457), whatever handler threw. A @ControllerAdvice with @ExceptionHandler methods handles exceptions from annotated controllers only. For router functions we can add onError to the builder or a filter. Duplicating the mapping in two places invites drift, so the more robust design is a single WebExceptionHandler, registered with a high precedence, that maps our exceptions for both styles, or a customised ErrorWebExceptionHandler, which Spring Boot already uses as the global fallback.

Java
@Component
@Order(-2) // before Boot's DefaultErrorWebExceptionHandler (-1)
class ProblemExceptionHandler implements WebExceptionHandler {
private final ObjectMapper json;
ProblemExceptionHandler(ObjectMapper json) { this.json = json; }
public Mono<Void> handle(ServerWebExchange ex, Throwable e) {
ProblemDetail p = switch (e) {
case NotFoundException n -> ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, n.getMessage());
case ConstraintViolationException v -> ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, v.getMessage());
default -> null;
};
if (p == null) return Mono.error(e); // let the next handler deal with it
ex.getResponse().setStatusCode(HttpStatusCode.valueOf(p.getStatus()));
ex.getResponse().getHeaders().setContentType(MediaType.APPLICATION_PROBLEM_JSON);
byte[] body = json.writeValueAsBytes(p); // checked exception handling omitted for brevity
return ex.getResponse().writeWith(Mono.just(ex.getResponse().bufferFactory().wrap(body)));
}
}
// GET /persons/99 (annotated) -> 404 application/problem+json
// GET /orders/99 (functional) -> 404 application/problem+json

Notice one subtlety. If a @ControllerAdvice also handles NotFoundException, it will win for annotated controllers because it runs first, inside the dispatcher. So we either let the advice delegate to the same mapping code, or keep exception mapping only in the shared handler. The rule is one owner per exception type.

3Validation in Both Styles

Annotated controllers validate with @Valid on a @RequestBody, and binding failures become WebExchangeBindException. Router functions have no argument resolution, so a handler must call a Validator itself. To keep behaviour identical, we put both behind one small helper: the functional handler calls it explicitly, and the error it throws is mapped by the shared exception handler to the same 400 problem response that @Valid failures produce. A test for each style that posts an invalid body and asserts the exact response shape keeps the two in step.

Java
@Component
class BodyValidator {
private final Validator validator; // jakarta.validation.Validator
BodyValidator(Validator validator) { this.validator = validator; }
<T> Mono<T> validate(T body) {
var v = validator.validate(body);
return v.isEmpty() ? Mono.just(body) : Mono.error(new ConstraintViolationException(v));
}
}
// functional handler: req.bodyToMono(Order.class).flatMap(bodyValidator::validate).flatMap(...)

4Security and Documentation

Security is the easy part. Spring Security for WebFlux runs as a WebFilter configured by a SecurityWebFilterChain, so path-based rules such as pathMatchers("/admin/**").hasRole("ADMIN") apply to both styles automatically. Method security with @PreAuthorize, enabled by @EnableReactiveMethodSecurity, works on any Spring bean method that returns a Mono or Flux, including handler methods. The risk is in the details: a router function registered under an unexpected path can fall outside a path matcher, so we keep an explicit rule that denies anything not listed.

Documentation needs real work. springdoc-openapi discovers annotated controllers by reflection, but a router function is just a lambda, so springdoc cannot see its request and response types. We add @RouterOperations with one @RouterOperation per route on the router bean, naming the path, method, beanClass and beanMethod, or use springdoc's functional route builder. A CI check that compares the generated OpenAPI paths with the registered routes catches undocumented endpoints.

Each concern in both styles
ConcernAnnotated controllersRouter functions
Error format@ControllerAdvice or shared handleronError, filter, or shared handler
Validation@Valid on @RequestBodyexplicit Validator call
Security rulesSecurityWebFilterChainSecurityWebFilterChain (same)
Method security@PreAuthorize@PreAuthorize on handler beans
OpenAPI docsautomatic in springdoc@RouterOperation or springdoc builder
Rows where the right column differs are where drift happens.

5Pick One Style per Service

All of this is effort spent keeping two mechanisms aligned. The simplest design is one style per service: annotated controllers for most request-response APIs, router functions where explicit, composable routing is the point, such as a small edge service or routes built from configuration. A team can still justify a mix, for example a mostly annotated service with one streaming route that benefits from a functional filter chain, and then the shared exception handler, the validation helper and the documentation check are what keep it consistent.

6Follow-up questions

Does @ControllerAdvice ever apply to router functions?

No. @ControllerAdvice and @ExceptionHandler are processed by the adapter that invokes annotated handler methods. An exception from a handler function bypasses them and propagates to the router's own error handling, then to the WebExceptionHandler chain.

Where should tracing and request logging go?

In a WebFilter, or in the observability support Spring Boot already registers, so it runs for every request regardless of style. Putting them in a RouterFunction filter or in controller aspects would cover only half the endpoints.

How do you test that both styles behave the same?

With a small contract test suite that runs the same cases against one annotated endpoint and one functional endpoint: an unauthenticated call, a forbidden call, an invalid body, a missing resource and an unexpected exception, asserting identical status codes and problem bodies.

7Conclusion

In this answer, we saw that a mixed WebFlux service has one dispatcher but two handler types, and that mechanisms tied to annotated controllers, such as @ControllerAdvice and @Valid, do not reach router functions. We kept errors consistent with a shared WebExceptionHandler or a customised ErrorWebExceptionHandler, validated functional bodies with an explicit Validator behind a shared helper, relied on SecurityWebFilterChain for security in both styles, documented router functions with @RouterOperation, and concluded that one style per service is best unless there is a clear reason to mix.

What to say in the interviewAbout 90 seconds aloud

Open with

The key is knowing where each mechanism sits. Both styles go through the same WebFilter chain and the same DispatcherHandler, but annotated controllers and router functions are invoked by different adapters.

Then, if they want more

So @ControllerAdvice, @ExceptionHandler and @Valid only work for annotated controllers. For error handling, I'd have one owner for each exception type. Router functions can use onError in the builder or a RouterFunction filter, but to avoid two mappings drifting I'd put a shared WebExceptionHandler, or a customised ErrorWebExceptionHandler, ahead of Boot's default, mapping exceptions to ProblemDetail for both styles.

For validation, functional handlers must call a Validator explicitly, so I'd wrap it in a small helper that throws the same exception the shared handler turns into the same 400 that @Valid produces.

Security is easier: SecurityWebFilterChain is a web filter, so path rules cover both styles, and @PreAuthorize works on any bean, but I'd keep a deny-by-default rule so a new route can't fall outside the matchers.

Documentation needs work: springdoc can't infer router functions, so I'd add @RouterOperation annotations and a CI check that every registered route appears in the OpenAPI spec. And I'd add contract tests that hit one endpoint of each style with the same bad requests and compare responses.

But honestly my first recommendation is to pick one style per service unless there's a clear reason, because all of this is effort spent keeping two mechanisms in step.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your team mixes annotated controllers and router functions in one WebFlux service. How...": https://scrivio-interview-library.netlify.app/spring-boot/webflux/94efd4fd05/