使用 ConstraintValidator 在 Micronaut 中验证 lambda 请求

Validating a lambda request in Micronaut using ConstraintValidator

我有一个这样的处理程序和一个自定义注释 @ValidRequest:

@Introspected
public class MessageHandler extends MicronautRequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

  @Override
  public APIGatewayProxyResponseEvent execute(@ValidRequest APIGatewayProxyRequestEvent event) {
    return new APIGatewayProxyResponseEvent()
        .withStatusCode(200)
        .withHeaders(Collections.singletonMap("Content-Type", "application/json"))
        .withBody("OK");
  }

}

注释本身如下所示:

@Retention(RUNTIME)
@Constraint(validatedBy = {ValidRequestValidator.class})
public @interface ValidRequest {

  String message() default "Request is not valid";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};

}

验证器是这样的:

@Introspected
public class ValidRequestValidator implements ConstraintValidator<ValidRequest, APIGatewayProxyRequestEvent> {

  @Override
  public boolean isValid(
      @Nullable APIGatewayProxyRequestEvent event,
      @NonNull AnnotationValue<ValidRequest> annotationMetadata,
      @NonNull ConstraintValidatorContext context
  ) {
    if (event == null || event.getBody() == null || event.getBody().isEmpty()) {
      throw new RuntimeException("Incorrect request event");
    }
    return true;
  }

}

问题是验证被完全忽略了。我可以发送任何带有或不带有正文的事件,并且一切正常。我按照 Micronout 文档做了一切,有什么问题吗?

https://docs.micronaut.io/latest/guide/index.html#beanValidation

请从您的验证器中删除 @Introspect 并尝试按照我在下面所做的相同操作。

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
@Path("/somePath")
public Response workingWithSubscription( @Valid UpdateSubscription updateSubscription) {

@ValidUpdateSubscription
public class UpdateSubscription implements UpdateSubscriptionRequest {

}

@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = UpdateSubscriptionValidator.class)
@Documented
public @interface ValidUpdateSubscription {

    int ERROR_CODE = 1111;

    String message() default "Null value";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    int errorCode() default ERROR_CODE;

    Response.Status status() default Response.Status.BAD_REQUEST;
}

@Named
@ApplicationScoped
public class UpdateSubscriptionValidator implements ConstraintValidator<ValidUpdateSubscription, UpdateSubscription> {

    @Override
    public boolean isValid(UpdateSubscription value, ConstraintValidatorContext context) {

        return true/OR/false;
    }
}