ConstraintValidator自定义注解

  自定义接口

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
public @interface Password {

    String type() default "default";

    /**
     * 默认错误消息
     *
     * @return
     */
    String message() default "密码过于简单";

    /**
     * 分组
     *
     * @return
     */
    Class<?>[] groups() default {};

    /**
     * 负载
     *
     * @return
     */
    Class<? extends Payload>[] payload() default {};
}

 

  实现自定义接口

  type用于标识符 通过constraintAnnotation.type()对type初始化

  下面判断type就可以对注解进行扩展

public class PasswordValidator implements ConstraintValidator<Password, Object> {

    private String type;
    @Override
    public void initialize(Password constraintAnnotation) {
        type = constraintAnnotation.type();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        switch (type){
            case "1":
                if(value.equals("123")){
                    return true;
                }
                return false;
            case"2":
                System.out.println(456);
                return true;
       default: System.out.println("谢谢"); true; } return true; } }

  定义实体类

  定义好type值

@Data
public class Text {
    @NotBlank
    @Password(type = "1",message = "不存在")
    private String text;
}

  controller

@GetMapping("/test")
public String test(@Validated Text text){
  System.out.println(text);
  return text.getText();
}

 

  如果spring自带的@Validated 不生效可能版本冲突注解不生效  导入如下依赖 就可以解决不生效问题

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>
posted @ 2020-09-28 23:56  小小小小丑。  阅读(1711)  评论(0编辑  收藏  举报