2020-06-25

自定义注解(参数类型校验)

public class FlagValidatorClass implements ConstraintValidator {
    private String[] values;
    @Override
    public void initialize(FlagValidator constraintAnnotation) {
        values = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        boolean isValid = false;
        if(value == null){
            return false;
        }
        for (int i = 0; i < values.length; i++) {
            if(values[i].equals(String.valueOf(value))){
                isValid = true;
                break;
            }
        }
        return isValid;
    }
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Constraint(validatedBy =  FlagValidatorClass.class)
public @interface FlagValidator {
    String[] value() default {};
    String message() default "flag is not found";
    Class[] groups() default {};
    Class[] payload() default {};
}
@FlagValidator(value = {"0","1"},message = "请求类型不正确")
private Integer requireType;

你可能感兴趣的:(2020-06-25)