美文网首页
自定义validation注解进行校验

自定义validation注解进行校验

作者: 纸箱子的一 | 来源:发表于2018-12-04 15:37 被阅读0次

    有时候我们需要自定义注解进行校验前端的入参
    依赖

    <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
    </dependency>
    

    demo 自定义注解

    import javax.validation.Constraint;
    import javax.validation.Payload;
    import java.lang.annotation.*;
    
    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = CheckDecisionValidator.class)
    @Documented
    public @interface DecisionCheck {
    
        String message() default "请传入符合要求的decision值";
    
        Class<?>[] groups() default { };
    
        Class<? extends Payload>[] payload() default { };
    
    }
    

    实现

    import javax.validation.ConstraintValidator;
    import javax.validation.ConstraintValidatorContext;
    
    public class CheckDecisionValidator implements ConstraintValidator<DecisionCheck, Byte> {
        @Override
        public void initialize(DecisionCheck constraintAnnotation) {
        }
    
        @Override
        public boolean isValid(Byte value, ConstraintValidatorContext context) {
            return DecisionEnum.valueOf(value) != null;
        }
    }
    
    public enum DecisionEnum {
    
        /**
         * Decision-yes
         */
        YES((byte)1,"同意"),
        /**
         * Decision-no
         */
        NO((byte)0,"否认");
    
        private Byte type;
        private String description;
    
        DecisionEnum(Byte type, String description) {
            this.type = type;
            this.description = description;
        }
    
        public static DecisionEnum valueOf(Byte value) {
            switch (value) {
                case 0:
                    return DecisionEnum.NO;
                case 1:
                    return DecisionEnum.YES;
                default:
                    return null;
            }
        }
    
        public Byte getType() {
            return type;
        }
    
        public DecisionEnum setType(Byte type) {
            this.type = type;
            return this;
        }
    
        public String getDescription() {
            return description;
        }
    
        public DecisionEnum setDescription(String description) {
            this.description = description;
            return this;
        }
    }
    

    相关文章

      网友评论

          本文标题:自定义validation注解进行校验

          本文链接:https://www.haomeiwen.com/subject/vygmcqtx.html