Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate custom annotation attributes?

Tags:

java

spring

I have one custom field annotation class with two attributes like below:

public @interface Field {
    String type();
    int order();
}

I wanted to validate order, it should not be a negative value and should not repeat, for example:

class User {
    @Field(uiType = "TEXT", order = 1)
    private String fName;

    @Field(uiType = "TEXT", order = 2)
    private String lName;
}

Can anyone help me to do it?

like image 875
Venu Annaram Avatar asked Nov 03 '22 19:11

Venu Annaram


1 Answers

Although this isn't quite what the Bean Validation API is for, you can perform this validation with it. I'm assuming you'd use Hibernate Validator, the reference implementation of the BV API.

You can get the negative check out of the way using a simple validator. Modify @Field to

@Constraint(validatedBy = MyFieldValidator.class)
public @interface Field {
    String type();
    int order();
}

and create a MyFieldValidator class as follows

public class MyFieldValidator implements ConstraintValidator<Field, Object> {

    private int order;

    @Override
    public void initialize(Field annotation) {

        this.order = annotation.order();

        if (this.order < 0) {
          // blow up
        }
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {

        return true;
    }
}

If you then put the object through a validator, e.g. using Validation.buildDefaultValidatorFactory().getValidator().validate(someUser), any negative order annotation attributes will fail.

Preventing repetition is trickier. The sanest option is to put a validation annotation at the User class level, then use reflection to get the annotations one by one. The advantage of using the class level annotation is that it gives you a simple way to tell Hibernate Validator which classes to check. The not-so-great part is that you might forget to annotate the class.

like image 191
Emerson Farrugia Avatar answered Nov 15 '22 05:11

Emerson Farrugia