springboot 自定义校验注解,可校验传入值是否满足条件

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {FixedValueValidator.FixedValueValid.class})

public @interface FixedValueValidator {

    String message() default "FixedValue's value is invalid";

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

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

    String[] fixedValue();

    class FixedValueValid implements ConstraintValidator<FixedValueValidator, Object> {

        String[] fixedValue = null;

        @Override
        public void initialize(FixedValueValidator validData) {
            this.fixedValue = validData.fixedValue();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintContext) {
            if (fixedValue == null || fixedValue.length == 0) {
                return false;
            }

            if (value == null) {
                return true;
            }

            boolean flag = false;
            for (String str : fixedValue) {
                if (String.valueOf(value).equals(String.valueOf(str))) {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
    }
}

使用方式:

  @FixedValueValidator(fixedValue = {"0", "1", "2", "3", "4"}, message = "优先级类型有误")
  private Long priorityLevel;
ValidatorUtils.validateEntity(object);

以下为校验工具类

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @ClassName: ValidatorUtils
 * @Author: dujiayu
 * @Description:
 * @Date: 2022/10/27 14:29
 * @Version: 1.0
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws ValidatorException 校验不通过,则报ValidatorException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws ValidatorException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator()
                    .next();
            throw new ValidatorException(constraint.getMessage());
        }
    }

    /**
     * 添加
     */
    public interface Insert {
    }

    /**
     * 修改
     */
    public interface Update {
    }
}

你可能感兴趣的:(spring,boot,工具类,随笔,spring,boot,java,后端)