Skip to content

How to reuse validator class in spring boot app?

I am currently writing custom validator for Spring Boot app and its idea is mainly to do some validations depending on other validations. For example, I want one field to be @NotNull if some other field is null, but the idea is to make it more generic, so that this conditional validations can be changed. For this purpose I tried to use validation classes from annotations, that already exist, like @NotNull or @Size, but turned out they don’t have them:

@Constraint(validatedBy = { })
public @interface NotNull {

What do these braces after validatedBy mean? How can I get the Validator that this interface uses?



If you create your own constraint annotation, you should define your validator in @Constraint using validatedBy attribute.

Validators for built-in constraint-annotations are registred in ConstraintHelper class in its constructor, therefore the curly brackets are empty. For example, validator registration for @NotNull annotation in ConstraintHelper constructor looks so:

putConstraint( tmpConstraints, NotNull.class, NotNullValidator.class );

If you want to see built-in implementations of javax.validation.ConstraintValidator, go to org.hibernate.validator.internal.constraintvalidators package. Or if you are using Intellij Idea:

Right click on declaration of ConstraintValidator -> Go To -> Implementation(s)

So, to reuse this validators you can create your custom annotation and put built-in annotations on it:

@Constraint(validatedBy = { })
public @interface NotNullAndNotEmpty {
    String message() default "some message";
    Class<?>[] groups() default {};
    Class<? extends Payload> [] payload() default {};

, or you can initialize some built-in validator in your custom validator and call its isValid() method in your isValid() method.