一、自定义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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。