I have a spring rest service that receives a list of elements, like this:
@RequestMapping(value = "/foobar", method = RequestMethod.PUT)
public ... foobar(
@Valid @RequestBody(required = true) List<Exp> listDto) {
I created an annotation @MyConstraint,
@Constraint(validatedBy = MyValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraint{
String message() default "differents in list";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and
public class MyValidator
implements ConstraintValidator<MyConstraint, List<Exp>> {
@Override
public boolean isValid(List<Exp> values, ConstraintValidatorContext context) {
return values.stream() //
.map(Exp::getExpedientes) //
.map(G::getIdArea) //
.distinct() //
.count() != 1;// more than one
}
@Override
public void initialize(MyConstraint constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
}
@MyConstraint
public class Exp {
private List<G> expedientes;
}
public class G {
private Integer idArea;
}
but when I make a request to my web service, the validation is not being executed, even setting a return false;, the request is received, am I missing something to indicate the execution of the validation?
Just annotating
@Valid
on the method argument is not enough . You also have to annotate@Validated
at the controller class level in order to enable the method validation. Do you miss it ? Something like the following :It is mentioned at here :