温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

自定义@interface及groups校验

发布时间:2020-06-22 12:56:47 来源:网络 阅读:552 作者:梦Scarlett 栏目:软件技术

一、自定义annotation

摘自:http://elim.iteye.com/blog/1812584

  1. @Target({ElementType.FIELD, ElementType.METHOD})  

  2. @Retention(RetentionPolicy.RUNTIME)  

  3. @Constraint(validatedBy=MinValidator.class)  

  4. public @interface Min {  

  5.    

  6.     int value() default 0;  

  7.      

  8.     String message();  

  9.      

  10.     Class<?>[] groups() default {};  

  11.      

  12.     Class<? extends Payload>[] payload() default {};  

  13. }  



  1. public class MinValidator implements ConstraintValidator<Min, Integer> {  

  2.    

  3.     private int minValue;  

  4.      

  5.     public void initialize(Min min) {  

  6.        // TODO Auto-generated method stub  

  7.        //把Min限制类型的属性value赋值给当前ConstraintValidator的成员变量minValue  

  8.        minValue = min.value();  

  9.     }  

  10.    

  11.     public boolean isValid(Integer value, ConstraintValidatorContext arg1) {  

  12.        // TODO Auto-generated method stub  

  13.        //在这里我们就可以通过当前ConstraintValidator的成员变量minValue访问到当前限制类型Min的value属性了  

  14.        return value >= minValue;  

  15.     }  

  16.    

  17. }  

  18. public class User {  

  19.      

  20.     private int age;  


  21.     @Min(value=8, message="年龄不能小于8岁")  

  22.     public int getAge() {  

  23.        return age;  

  24.     }  

  25.    

  26.     public void setAge(int age) {  

  27.        this.age = age;  

  28.     }  

  29.   

  30. }  


二、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


向AI问一下细节

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

AI