千家信息网

自定义@interface及groups校验

发表于:2025-01-31 作者:千家信息网编辑
千家信息网最后更新 2025年01月31日,一、自定义annotation摘自:http://elim.iteye.com/blog/1812584@Target({ElementType.FIELD, ElementType.METHOD})
千家信息网最后更新 2025年01月31日自定义@interface及groups校验

一、自定义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. int value() default 0;

  6. String message();

  7. Class[] groups() default {};

  8. Classextends Payload>[] payload() default {};

  9. }



  1. public class MinValidator implements ConstraintValidator {

  2. private int minValue;

  3. public void initialize(Min min) {

  4. // TODO Auto-generated method stub

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

  6. minValue = min.value();

  7. }

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

  9. // TODO Auto-generated method stub

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

  11. return value >= minValue;

  12. }

  13. }

  14. public class User {

  15. private int age;


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

  17. public int getAge() {

  18. return age;

  19. }

  20. public void setAge(int age) {

  21. this.age = age;

  22. }


  23. }


二、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> set = validator.validate(student,First.class);      for (ConstraintViolation constraintViolation : set) {          System.out.println(constraintViolation.getMessage());      }}


参考:

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

http://blog.csdn.net/gaoshanliushui2009/article/details/50667017


0