我正在使用ConstraintValidator实现,如下所示,用于验证Spring Boot REST服务的请求对象
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = MyRequestValidator.class)
@Documented
public @interface MyRequestValidation {
String message() default "Mandatory fields missing";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class MyRequestValidator
implements
ConstraintValidator<MyRequestValidation, MyRequest>{
@Override
public void initialize(MyRequestValidation constraintAnnotation) {
// Nothing to do here
}
@Override
public boolean isValid(MyRequest myRequest, ConstraintValidatorContext context) {
//do some validation
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("Id can contain only alphabets and digits")
.addPropertyNode("id")
.addConstraintViolation();
}
}
//REST end point
public interface RestApi{
@Produces(MediaType.XML)
@Consumes(MediaType.XML)
@POST
MyResponse action(@MyRequestValidation MyRequest myRequest);
}
@Component
public class RestApiImpl implements RestApi {
..
}
这产生的输出为
[PARAMETER]
[myRequest.arg0.id]
[Id can contain only alphabets and digits]
无论如何,都可以生成JSON或XML消息(或基于REST端点上的@Produces批注)。我正在使用这些接口ConstraintValidatorContext的Hibernate实现