spring - 使用 Spring Reactive 时如何验证 Mono

标签 spring spring-mvc spring-boot spring-webflux spring-validator

我们正在为一个项目评估 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/

相关文章:

java - 有没有办法注入(inject)一个依赖项,该依赖项将根据注入(inject)的位置(使用 Spring 引导)使用特定的 bean?

java - 我可以在 spring java 应用程序中使用 docker 登录到外部文件吗?

java - spring - 使用谷歌 Guava 缓存

java - 想使用 Java 制作网站,我应该实现 struts 吗?

java - 应用程序性能和 CLI

java - Spring Boot REST API 的指标收集

mysql - 删除并插入而不是更新

SpringMVC : Could not instantiate property type [java. lang.Double]自动增长嵌套属性路径

java - 如何使用 RedirectAttributes 在另一个 Controller 中调用一个 Controller 方法

java - RestClientTest 和 NoSuchBeanDefinitionException