Search code examples
javaspringhibernate-validator

Is it possible to pass validatedBy attribute to the annotation as a parameter?


I hard coded the validatedBy value as following.

@Constraint(validatedBy = ReminderValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyValidator{
    String message() default "{error.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Instead of hard coding the validatedBy value into my annotation interface, I want to pass it as a parameter something similar to the following.

@MyValidator(validatedBy = "ReminderValidator.class")
public class Reminder {
...
}

This will enable me to create just 1 annotation for all class validations. I will just provide different validator classes to the annotation to validate different classes. Is it possible to do something like this?


Solution

  • You can add multiple validators in the @Constraint annotation and it will pick the appropriate based on the object type.

    @Constraint(validatedBy = { ReminderValidator.class, PendingValidator.class } )
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyValidator{
        String message() default "{error.message}";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    And

    @MyValidator()
    public class Reminder {
        ...
    }
    
    @MyValidator()
    public class Pending {
        ...
    }
    

    Validator Examples

    public class ReminderValidator implements ConstraintValidator<MyValidator, Reminder> {
    ...
    
    public class PendingValidator implements ConstraintValidator<MyValidator, Pending> {
    ...