我们正在为一个项目评估 Spring 5,但不确定如何最好地验证 Mono
参数。传统上,我们一直使用 MethodValidationPostProcessor 来验证我们的方法参数,如下所示:
@Validated
@Service
public class FooService
@Validated(SignUpValidation.class)
public void signup(@Valid UserCommand userCommand) {
...
}
然后我们将在
ControllerAdvice
中处理异常或 ErrorController
,并将合适的 4xx 响应传递给客户端。但是当我将参数更改为
Mono
时,如下所示,它似乎不再起作用。@Validated
@Service
public class FooService
@Validated(SignUpValidation.class)
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {
...
}
据我了解 Spring Reactive,可能它实际上不应该工作。那么,验证
Mono
的 Spring 5 最佳实践是什么? s 和 Flux
es,然后发送一个合适的错误响应?
最佳答案
在回答这个问题之前,快不,void
在响应式(Reactive)应用程序中,您的方法的返回类型非常不寻常。看看这个,这个方法似乎应该异步执行实际工作,但该方法返回一个同步类型。我已将其更改为 Mono<Void>
在我的回答中。
As stated in the reference documentation , Spring WebFlux 确实支持验证。
但是这里的最佳实践有所不同,因为方法参数可以是 react 类型。如果方法参数尚未解析,则无法获得验证结果。
所以这样的事情不会真正起作用:
// 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)
一些更惯用且更易于与响应式(Reactive)运算符一起使用的东西:
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();
}
关于spring - 使用 Spring Reactive 时如何验证 Mono,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244769/