JavaBean Validation - Using Constraint Annotations in Superclasses and Interfaces (Constraint Inheritance)

[Updated: Aug 11, 2017, Created: Aug 11, 2017]

The constraint annotations can be placed in an interface or a superclass hierarchy. The constraint annotations are applied cumulatively. Constraints declared in a superclass getter are validated along with any constraints defined on an overridden version of the getter.

Example

public interface Employee {

  String getName();

  @Valid
  @NotNull
  PhoneNumber getPhoneNumber();

  @NotNull
  String getDept();
}
public class PhoneNumber {
  @NotNull
  private String type;
  @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}")
  private String number;

  public PhoneNumber(String type, String number) {
      this.type = type;
      this.number = number;
  }
    .............
}
public class Person {
  @NotNull
  @Size(min = 1, max = 300)
  private String name;

  public Person(String name) {
      this.name = name;
  }
    .............
}
public class EmployeeImpl extends Person implements Employee{
  private PhoneNumber phoneNumber;
  private String dept;

  public EmployeeImpl(String name, PhoneNumber phoneNumber, String dept) {
      super(name);
      this.phoneNumber = phoneNumber;
      this.dept = dept;
  }
    .............
}

The main class

public class ExampleMain {
  public static void main(String[] args) {
      Validator validator = createValidator();
      Employee employee = new EmployeeImpl("",
              new PhoneNumber("cell", "234-3334"), null);
      Set<ConstraintViolation<Employee>> violations = validator.validate(employee);
      violations.forEach(ExampleMain::printError);
  }

  private static void printError(ConstraintViolation<?> violation) {
      System.out.println(violation.getPropertyPath()
              + " " + violation.getMessage());
  }

  private static Validator createValidator() {
      Configuration<?> config = Validation.byDefaultProvider().configure();
      ValidatorFactory factory = config.buildValidatorFactory();
      Validator validator = factory.getValidator();
      factory.close();
      return validator;
  }
}

Output

name size must be between 1 and 300
dept may not be null
phoneNumber.number must match "\d{3}-\d{3}-\d{4}"

Example Project

Dependencies and Technologies Used :

  • hibernate-validator 5.2.4.Final: Hibernate's Bean Validation (JSR-303) reference implementation.
  • javax.el-api 2.2.4 Expression Language API 2.2
  • javax.el 2.2.4 Expression Language 2.2 Implementation
  • JDK 1.8
  • Maven 3.3.9

Constraint Inheritance Validation Example Select All Download
  • constraint-inheritance-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also