Spring 集成 webflux - 验证输入 JSON 正文

Spring Integration webflux - validate input JSON body

以下是我的应用配置

@SpringBootApplication
class DemoApplication {

    static void main(String[] args) {
        SpringApplication.run(DemoApplication, args)
    }


    @Bean
    IntegrationFlow startHeatToJiraFlow() {
        IntegrationFlows
                .from(WebFlux.inboundGateway("/input1")
                .requestMapping { m -> m.methods(HttpMethod.POST).consumes(MediaType.APPLICATION_JSON_VALUE) }
                .requestPayloadType(ResolvableType.forClassWithGenerics(Mono, ServiceInput))
        )
                .channel("inputtestchannel")
                .get()
    }

    @ServiceActivator(inputChannel = "inputtestchannel")
    Map replyMessage() {
        return [success: true]
    }


    class ServiceInput {
        @NotBlank
        String input1
        @NotBlank
        String input2
    }
}

我希望以下 curl 请求给我一个错误,因为我没有在正文中提供输入 JSON。

curl  -X POST localhost:8080/input1 -H "Content-Type:application/json"

相反,我收到了 200 响应

{"success":true}

我在这里做错了什么?

WebFlux DSL 不支持验证。您可以将响应作为处理顺序的一部分进行验证,如 validation section of the webflux docs.

中所述

将其插入 Spring 集成的示例如下所示:

@EnableIntegration
@Configuration
class ValidatingFlowConfiguration {

  @Autowired
  Validator validator

  @Bean
  Publisher<Message<String>> helloFlow() {
    IntegrationFlows
        .from(
            WebFlux
                .inboundGateway("/greet")
                .requestMapping { m ->
                  m
                      .methods(HttpMethod.POST)
                      .consumes(MediaType.APPLICATION_JSON_VALUE)
                }
                .requestPayloadType(ResolvableType.forClassWithGenerics(Flux, HelloRequest))
                .requestChannel(greetingInputChannel())
        )
        .toReactivePublisher()
  }

  @Bean
  MessageChannel greetingInputChannel() {
    return new FluxMessageChannel()
  }

  @ServiceActivator(
      inputChannel = "greetingInputChannel"
  )
  Flux<String> greetingHandler(Flux<HelloRequest> seq) {
    seq
        .doOnNext { HelloRequest it -> validate(it) }
        .log()
        .map { "Hello, ${it.name}" as String }
  }

  void validate(HelloRequest request) {
    Errors errors = new BeanPropertyBindingResult(request, "request")
    validator.validate(request, errors);
    if (errors.hasErrors()) {
      throw new ServerWebInputException(errors.toString());
    }
  }
}

@ToString(includeNames = true)
@Validated
class HelloRequest {

  @NotEmpty
  String name
}

如果要导入,请参阅 gist