Java validation API: skip some rules without changing bean definition

I have an object in the jar API that I cannot change:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;
}

      

In my code, I need to use this object and validate the data internally, but for example I want the password to be blank. I cannot remove @NotNull from the class (and I cannot define groups for a given constraint). How can I affect the validation without redefining it from scratch?

+3


source to share


1 answer


One possible solution is to override the class-specific constraint definition using either the constraint constraint XML file or the specific Hibernate Validator API.

As described in the documentation, you can override specific annotations (like the password field annotation) and leave the rest untouched.

<constraint-mappings ...>

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

      



further reading:

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

+4


source







All Articles