JSR 303 cascade validation through inheritance
March 06, 2012 12:22:48 Last update: March 06, 2012 12:22:48
When a bean class inherits another class, the validation rules of the parent class is automatically executed when a child class bean is validated.
As an example, I create a class named
Now validate
Test with "
As an example, I create a class named
AccountPerson, which inherits the Person class with the addition of an email field (src/main/java/com/example/AccountPerson.java in Maven project):
package com.example; import javax.validation.constraints.NotNull; public class AccountPerson extends Person { @NotNull private String email; public AccountPerson(String name, String email) { super(name); this.email = email; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } }
Now validate
AccountPerson with a JUnit test (src/test/java/com/example/AccountPersonTest.java in Maven project):
package com.example; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class AccountPersonTest { private Validator validator; @Before public void setUp() { ValidatorFactory f = Validation.buildDefaultValidatorFactory(); validator = f.getValidator(); } @Test public void testNameNull() { AccountPerson p = new AccountPerson(null, "a@b.com"); Set<ConstraintViolation<AccountPerson>> violations = validator.validate(p); assertEquals(1, violations.size()); } @Test public void testNameEmailNull() { AccountPerson p = new AccountPerson(null, null); Set<ConstraintViolation<AccountPerson>> violations = validator.validate(p); assertEquals(2, violations.size()); } }
Test with "
mvn clean test" and you'll see that the validation rules of the Person class are executed when an AccountPerson bean is validated.