Spring MVC has the ability to automatically validate @Controller
inputs. In previous versions it was up to the developer to manually
invoke validation logic.
But in your case , you are trying to validate a DTO object in which case , springboot might not be automatically binding your validator to your model and call the validator.So, in that case, you will need to manually bind the object to the validator.
or you can manually invoke the validator on a bean like :
@AutoWired
Validator validator;
...
validator.validate(book);
You can define a custom validator in springboot for model classes if you want and use annotations :
@Documented
@Constraint(validatedBy = CustomDataValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDataConstraint {
String message() default "Invalid data";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and then define a validator class like :
public class CustomDataValidator implements
ConstraintValidator<CustomDataConstraint, String> {
@Override
public void initialize(CustomDataConstraint data) {
}
@Override
public boolean isValid(String field,
ConstraintValidatorContext cxt) {
return field!= null;
}
}
Your validator class must implement the ConstraintValidator
interface and must implement the isValid
method to define the validation rules, define the validation rules can be anything as you wish.Then, you can simply add the annotation to your field like :
@CustomDataConstraint
private String name;