如果要指定校验顺序,可通过groups来控制。
- 新建几个Group接口
public interface Group1 {
}
public interface Group2 {
}
public interface Group3 {
}
- 新增一个GroupSequence
@GroupSequence({
// 默认的必须加上,不然没有指定groups的注解不会生效
Default.class,
Group1.class,
Group2.class,
Group3.class,
})
public interface ValidationGroupSequence {
}
使用方式:
validator.validate(obj, ValidationGroupSequence.class);
测试用例:
import junit.framework.TestCase;
import org.hibernate.validator.constraints.Length;
import javax.validation.ConstraintViolation;
import javax.validation.GroupSequence;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Set;
/**
* @author tanghc
*/
public class ValidatorTest extends TestCase {
private static javax.validation.Validator validator;
static {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
/**
* 测试JSR-303注解校验顺序,校验顺序: Group1~GroupN
*/
public void testValidate() {
Set<ConstraintViolation<User>> set = validator.validate(new User("1", 1), ValidationGroupSequence.class);
if (set != null && set.size() > 0) {
ConstraintViolation<User> oneError = set.iterator().next();
String errorMsg = oneError.getMessage();
throw new IllegalArgumentException(errorMsg);
}
}
private static class User {
// 如果字段为空,无论如何都会命中这个
@NotBlank(message = "NotBlank", groups = Group1.class)
// 优先校验Group2
// 可交换下面Group2,Group3,看下校验顺序
@Length(min = 2, max = 20, message = "length must 10~20", groups = Group2.class)
@Pattern(regexp = "[a-zA-Z]*", message = "name must letters", groups = Group3.class)
private String name;
@Min(value = 1, message = "min 1")
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public interface Group1 {
}
public interface Group2 {
}
public interface Group3 {
}
@GroupSequence({
// 默认的必须加上,不然没有指定groups的注解不会生效
javax.validation.groups.Default.class,
Group1.class,
Group2.class,
Group3.class,
})
public interface ValidationGroupSequence {
}
}