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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM