使用 Spring Reactive 时如何验证 Mono

San*_*jay 4 spring spring-mvc spring-validator spring-boot spring-webflux

我们正在为一个项目评估 Spring 5,但不确定如何最好地验证Mono参数。传统上,我们一直使用MethodValidationPostProcessor来验证我们的方法参数,如下所示:

@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public void signup(@Valid UserCommand userCommand) {

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后我们将在ControllerAdviceor 中处理异常ErrorController,并将合适的 4xx 响应传递给客户端。

但是当我将参数更改为 时Mono,如下所示,它似乎不再起作用。

@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {

    ...
}
Run Code Online (Sandbox Code Playgroud)

据我了解 Spring Reactive,可能它实际上不应该工作。那么,验证Monos 和Fluxes 然后发送合适的错误响应的Spring 5 最佳实践是什么?

Bri*_*zel 6

在回答这个问题之前,请快速回答,void您的方法的返回类型在反应式应用程序中非常不寻常。看看这个,这个方法似乎应该异步执行实际工作,但该方法返回一个同步类型。我已将其更改为Mono<Void>答案。

正如参考文档中所述,Spring WebFlux 确实支持验证。

但是这里的最佳实践有所不同,因为方法参数可以是反应类型。如果方法参数尚未解析,则无法获得验证结果。

所以这样的事情不会真正起作用:

// can't have the BindingResult synchronously,
// as the userCommand hasn't been resolved yet
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand, BindingResult result)

// while technically feasible, you'd have to resolve 
// the userCommand first and then look at the validation result
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand, Mono<BindingResult> result)
Run Code Online (Sandbox Code Playgroud)

一些更惯用和更容易与反应式运算符一起使用的东西:

public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {
    /*
     * a WebExchangeBindException will flow through the pipeline
     * in case of validation error.
     * you can use onErrorResume or other onError* operators
     * to map the given exception to a custom one
     */
    return userCommand.onErrorResume(t -> Mono.error(...)).then();
}
Run Code Online (Sandbox Code Playgroud)