Search code examples
javaspringvalidationbean-validationspring-validator

When to use Bean Validation vs a customized validation framework?


I am validating fields of my Data Access Object classes. In one attempt, I have started adding Bean Validation annotations to the properties (@NotNull, @NotBlank, @Min, @Max and so on). I also have more annotations Jackson (JsonProperty (..)) for swagger library and documentation (@Api (...)). In my opinion the class was very "dirty" with many annotations (each property has at least three annotations). Example of one field:

@JsonProperty("ownName")
@Api(description="it is my own name" required=true)
@Valid
@NotNull
private SomeObject object; 

In another attempt, I have performed my own validation with the Spring Validator interface. If a custom validator such as the Spring Interface is used it seems to be cleaner and also allows you freedom to generate more than one validator for different situations. Also, the class does not seem to be so overloaded with annotations and validations are independent of the class. Example of Validator:

public class UserValidator implements Validator {

    @Override
    public boolean supports(Class<?> arg0) {
        return User.class.isAssignableFrom(arg0);
    }

    @Override
    public void validate(Object obj, Errors error) {
        User user = (User) obj;
        if(user.getPassword().length() < 10)
        {
            error.reject("Password must be lesser than 10");
        }

        //more validations....

    }
}
  • When would you use one or another?
  • What are the pros and cons of each?

Solution

  • I think it is a matter of taste and use case. I agree that sometimes it feels one ends up in some sort of annotation overload.

    Some reasons for using Bean Validation are that it is a standard. The constraint annotations are standardized and many frameworks integrate with it, for example JPA in case you want to add yet another annotation based framework ;-)

    Using something like Spring binds you to a specific library/framework. Your code will be less portable. If you of course never see a scenario where you would leave Spring behind, this might not matter.

    Of course you could do something home grown altogether, but in this case you need to write the whole integration code into for example Spring, REST, JPA, etc.

    Also writing a general purpose validation framework is not trivial. There are many things to consider.