Java 验证 API: 跳过一些规则而不改变 bean 定义

Java validation API: skip some rules without changing bean definition

我在 API jar 中有一个对象,我无法更改:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;
}

在我的代码中我需要使用这个对象并验证里面的数据,但是,例如,我想让密码为空。我无法从 class 中删除 @NotNull(并且我无法为给定约束定义组)。如何在不从头重新定义验证的情况下影响验证?

一种可能的解决方案是使用约束映射 xml 文件或特定于 Hibernate Validator 的 API.

覆盖特定 class 的约束定义

如文档中所述,您可以覆盖特定注释(如密码字段注释)并保持其他注释不变。

<constraint-mappings ...>

  <bean class="User" ignore-annotations="false">
    <field name="password" ignore-annotations="true">
        ... new annotations
    </field>
  </bean>
</constraint-mappings>

进一步阅读:

http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-xml-configuration.html#section-mapping-xml-constraints

http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-specifics.html#section-programmatic-api