如何混合使用 Spring Validator 和 JSR 303

How mix Spring Validator and JSR 303

我想通过使用注释和 Spring 验证器来执行验证。

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());
}

我原以为输出中有两个错误,但我只得到 Spring 验证器的错误。

我错过了什么?

DataBinder 验证器最初是空的。 Implementation

尝试添加 JSR 303 验证器,如下所示:

 ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

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