一、自定义annotation
摘自:http://elim.iteye.com/blog/1812584
-
@Target({ElementType.FIELD, ElementType.METHOD})
-
@Retention(RetentionPolicy.RUNTIME)
-
@Constraint(validatedBy=MinValidator.class)
-
public @interface Min {
-
-
int value() default 0;
-
-
String message();
-
-
Class<?>[] groups() default {};
-
-
Class<? extends Payload>[] payload() default {};
-
}
-
public class MinValidator implements ConstraintValidator<Min, Integer> {
-
-
private int minValue;
-
-
public void initialize(Min min) {
-
// TODO Auto-generated method stub
-
//把Min限制类型的属性value赋值给当前ConstraintValidator的成员变量minValue
-
minValue = min.value();
-
}
-
-
public boolean isValid(Integer value, ConstraintValidatorContext arg1) {
-
// TODO Auto-generated method stub
-
//在这里我们就可以通过当前ConstraintValidator的成员变量minValue访问到当前限制类型Min的value属性了
-
return value >= minValue;
-
}
-
-
}
-
public class User {
-
-
private int age;
-
@Min(value=8, message=“年龄不能小于8岁”)
-
public int getAge() {
-
return age;
-
}
-
-
public void setAge(int age) {
-
this.age = age;
-
}
-
-
}
二、group校验
public class Student implements Serializable { private static final long serialVersionUID = 1L; @NotBlank(message = "名称不能为空", groups = { First.class }) private String name; @NotBlank(message = "年龄不能为空", groups = { Second.class }) private String age; ...省略get set方法 } public @interface First { } public @interface Second { } public static void main(String[] args){ Student student = new Student(); ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); Validator validator = vf.getValidator(); Set<ConstraintViolation<student>> set = validator.validate(student,First.class); for (ConstraintViolation<student> constraintViolation : set) { System.out.println(constraintViolation.getMessage()); } }
参考:
http://elim.iteye.com/blog/1812584
http://blog.csdn.net/gaoshanliushui2009/article/details/50667017
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/191869.html