您好,登錄后才能下訂單哦!
一、自定義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賦值給當(dāng)前ConstraintValidator的成員變量minValue
minValue = min.value();
}
public boolean isValid(Integer value, ConstraintValidatorContext arg1) {
// TODO Auto-generated method stub
//在這里我們就可以通過當(dāng)前ConstraintValidator的成員變量minValue訪問到當(dāng)前限制類型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校驗(yàn)
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
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。