I'm trying to validate multiple fields using spring boot constraintValidator. But it doesn't buzz with no error in it.
Can someone please help me find it out..
Controller
@PostMapping("/greetings")
public Greeting greeting(@RequestBody Greeting greeting) {
System.out.println(greeting);
return greeting;
}
Bean thats needs to be validated
@GreetingAnnotation
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
Annotation
@Constraint(validatedBy = GreetingValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GreetingAnnotation {
String message() default "Field is required";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Validator
public class GreetingValidator implements ConstraintValidator<GreetingAnnotation, Greeting > {
@Override
public boolean isValid(Greeting greeting, ConstraintValidatorContext context) {
return greeting.getId() >=0 && greeting.getContent().length() >=100; // Never gets called
}
}
NOTE: This is just a sample stub for validating an object
Thanks in advance
Are you using @Validated at your controller level ?
If Not they add it. It will work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.