使用ConstraintValidator在Micronaut中验证lambda请求



我有一个这样的处理程序和一个自定义注释@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;
}
}

相关内容

  • 没有找到相关文章

最新更新