Search code examples
javaspringbean-validationspring-validator

How mix Spring Validator and JSR 303


I want to perform a validation both by using annotations and Spring Validator.

Product.java

public class Product {
    private int id;
    @NotNull(message = "cannot be null")
    private String desc;

    // getters and setters
}

ProductValidator.java

public class ProductValidator implements Validator {
    public boolean supports(Class<?> aClass) {
        return Product.class.equals(aClass);
    }

    public void validate(Object obj, Errors errors) {
        Product p = (Product) obj;
        if (p.getId() <= 0) {
            errors.rejectValue("id", "id must be positive");
        }
    }
}

Main.java

public static void main(String[] args) {
    Product product = new Product();

    DataBinder binder = new DataBinder(product);
    binder.addValidators(new ProductValidator());
    binder.validate();

    System.out.println(binder.getBindingResult());
}

I was expecting two errors in the output but I get only the Spring Validator's one.

What am I missing?


Solution

  • DataBinder validators are initially empty. Implementation

    Try adding JSR 303 validator, something like this:

     ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    
     DataBinder binder = new DataBinder(product);
     binder.addValidators(new ProductValidator());
     binder.addValidators(new SpringValidatorAdapter(factory.getValidator()));
     binder.validate();