• 【java】实现自定义注解校验——方法一


    自定义注解校验的实现步骤:

    1.创建注解类,编写校验注解,即类似@NotEmpty注解
    2.编写自定义校验的逻辑实体类,编写具体的校验逻辑。(这个类可以实现ConstraintValidator这个接口,让注解用来校验)
    3.开启使用自定义注解进行校验。

    第一种实现自定义注解的方式:

    一、创建注解类:

    1、创建类时,选择Annotation类型

    在这里插入图片描述

    2、编写注解类

    编写注解类时,需要用到元注解来规定注解的实现方式等;

    package cn.hsa.bis.api.common.utils;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    /**
     * @Description 基础校验注解
     * @Author chenzz
     * @create 2020/3/6 19:43
     */
    //Target注解是指定当前自定义注解可以使用在哪些地方,这里仅仅让他可以使用在字段上;
    @Target(ElementType.FIELD)
    //指定当前注解保留到运行时;
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ValiInfo {
    
        /**
         * 最小长度
         */
        int minLen() default 0;
    
        /**
         * 最大长度
         */
        int maxLen() default 2147483647;
    
        /**
         * 非空校验
         */
        boolean notBlank() default false;
    
        /**
         * 字典校验
         */
        String codeType() default "";
    
        /**
         * 非法字符校验
         * 特殊字符:ascii码表中除字母、数字外的所有字符,顿号(、),间隔号(·)
         */
        String illegalCharRegExp() default ".*[\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f\\u3001\\u00b7]+.*";
    
        /**
         * 正则校验
         */
        String regexp() default "";
    
        /**
         * 字段含义
         */
        String mean() default "";
    
        /**
         * 汉字校验
         */
        String regexpChinese() default "";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    3、元注解 (编写注解类时,必须要明白的)

    刚创建出来的注解是不能使用的。因为我们不知道注解应该加在什么地方,在什么时间生效,所以就引出来元注解的概念。元注解就是注解的注解(有点绕口令的感觉)。专门用来注解注解类型。
    java的元注解:@Target,@Retention,@Documented,@Inherited

    @Target直接指明了该注解生效的位置,该参数没有default值,必填。参数是一个枚举类型
    在这里插入图片描述

    @Retention指明了注解生效的阶段
    在这里插入图片描述
    @Documented
    当我们用javaDoc生成API文档时,是否将该注解记录到API文档中。
    @Inherited
    这个注解是说,我们的注解是否需要被子类继承。是发生在子类和父类之间的一种注解。

    注意:当我们的注解作用域是Element.TYPE时,我们定义在类上的注解可以被子类继承。但是如果我们注解的作用域是Element.METHOD时,并且父类的该方法被子类重写,那作用在父类的注解不会被子类继承。所以如果我们在接口的方法中定义的注解,永远不会被实现类继承,因为实现类一定会重写接口中的方法。

    二、自定义注解校验逻辑的实现:

    这里有两种实现方式,
    一种是当注解仅仅作用在字段(属性)上生效时:可以在工具类中编写方法进行逻辑校验;
    另一种是当注解作用在方法上生效时,可以使用@Constraint注解,指明了校验类,进行校验;

    这里只实现第一种。

    第一种:当自定义注解仅仅作用在字段上生效时,在工具类中编写方法进行逻辑校验(在工作中用的比较多)

    public class ToolUtils {
        /**
         * 对象基础格式校验,针对带有valiInfo注解的属性
         * @param obj
         * @param ignoreFields 忽略校验的字段
         * @return: java.lang.StringBuffer
         * @author: chenzz
         * @date: 2020/4/22 23:36
         */
        public static StringBuffer valiObjStringField(Object obj, String[] ignoreFields) {
            StringBuffer errMsg = new StringBuffer();
            try {
                Set<String> ignoreFieldSet = new HashSet<>();
                ignoreFieldSet.add("class");
                if (null != ignoreFields) {
                    for (String field : ignoreFields) {
                        if (StringUtils.isNotBlank(field)) {
                            ignoreFieldSet.add(field);
                        }
                    }
                }
                PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(obj.getClass());
                for (PropertyDescriptor targetPd : propertyDescriptors) {
                    if (ignoreFieldSet.contains(targetPd.getName())) {
                        continue;
                    }
                    Method readMethod = targetPd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(obj);
                    ValiInfo valiInfo = obj.getClass().getDeclaredField(targetPd.getName()).getAnnotation(ValiInfo.class);
                    if (null == valiInfo) {
                        continue;
                    }
                    String mean = valiInfo.mean();
                    if (StringUtils.isBlank(mean)) {
                        mean = targetPd.getName();
                    }
                    // 空置校验
                    boolean isBlank = null == value || StringUtils.isBlank(value.toString());
                    if (valiInfo.notBlank()) {
                        if (isBlank) {
                            errMsg.append(String.format("【%s】不能为空;", mean));
                            continue;
                        }
                    } else {
                        if (isBlank) {
                            continue;
                        }
                    }
                    // 如果是字符串才进行下面的校验
                    if (!(value instanceof String)) {
                        continue;
                    }
                    String strValue = value.toString();
                    // 长度校验 最小长度为0
                    int len = strValue.length();
                    if (len < valiInfo.minLen()) {
                        errMsg.append(String.format("【%s(%s)】长度不能小于%d个字符;", mean, strValue, valiInfo.minLen()));
                        continue;
                    }
                    // 最大长度为2147483647
                    if (len > valiInfo.maxLen()) {
                        errMsg.append(String.format("【%s(%s)】长度不能超过%d个字符;", mean, strValue, valiInfo.maxLen()));
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(obj, strValue.substring(0, valiInfo.maxLen() - 1));
                        continue;
                    }
                    if (strValue.matches(valiInfo.illegalCharRegExp())) {
                        errMsg.append(String.format("【%s(%s)】中不能包含特殊字符;", mean, strValue));
                        continue;
                    }
                    if (StringUtils.isNotBlank(valiInfo.regexp()) && !strValue.matches(valiInfo.regexp())) {
                        errMsg.append(String.format("【%s(%s)】格式校验不通过;", mean, strValue));
                        continue;
                    }
                    // 校验是否存在汉字
                    if (StringUtils.isNotBlank(valiInfo.regexpChinese())) {
                        char c[] = strValue.toCharArray();
                        Pattern pattern = Pattern.compile(valiInfo.regexpChinese());
                        boolean flag = false;
                        for (int i = 0; i < c.length; i++) {
                            Matcher matcher = pattern.matcher(String.valueOf(c[i]));
                            if (matcher.matches()) {
                                flag = true;
                            }
                        }
                        if (flag) {
                            errMsg.append(String.format("【%s(%s)】入参存在汉字;", mean, strValue));
                            continue;
                        }
                    }
                    // 码值校验
                    if (StringUtils.isNotBlank(valiInfo.codeType())) {
                        if (DictUtil.isNotDict(valiInfo.codeType().toUpperCase(), strValue)) {
                            errMsg.append(String.format("【%s(%s)】不在代码表中;", mean, strValue));
                        }
                    }
                }
                return errMsg;
            } catch (IllegalAccessException e) {
                throw new BisException(BusinessConst.CALL_FAIL_TYPE_JC, "对象数据格式校验失败!");
            } catch (InvocationTargetException e) {
                throw new BisException(BusinessConst.CALL_FAIL_TYPE_JC, "对象数据格式校验失败!");
            } catch (NoSuchFieldException e) {
                throw new BisException(BusinessConst.CALL_FAIL_TYPE_JC, "对象数据格式校验失败!");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113

    三、使用自定义注解:

    自定义校验注解在代码中的应用

    1、在dto中使用:

    @Data
    public class PsnInsureInfoQueryDTO implements Serializable {
        private static final long serialVersionUID = -3173331123860803536L;
    
        /**
         * 缴费开始年月
         */
        @ValiInfo(mean = "缴费开始", minLen = 6, maxLen = 6, regexp = RegexpConst.REGEXP_YM)
        private String begnYm;
    
        /**
         * 单位编号
         */
        @ValiInfo(mean = "单位编号", minLen = 1, maxLen = 40, illegalCharRegExp = RegexpConst.ILLEGAL_CHAR_REGEXP_EMPNO, regexpChinese = RegexpConst.REGEXP_CHINESE)
        private String empNo;
    
        /**
         * 险种类型
         */
        @ValiInfo(mean = "险种类型", minLen = 1, maxLen = 3, codeType = "INSUTYPE", regexpChinese = RegexpConst.REGEXP_CHINESE)
        private String insutype;
    
        /**
         * 统筹区编码
         */
        @ValiInfo(mean = "统筹区编码", minLen = 6, maxLen = 6, codeType = "ADMDVS_PLC", regexpChinese = RegexpConst.REGEXP_CHINESE)
        private String poolarea;
    
        /**
         * 参保状态
         */
        @ValiInfo(mean = "参保状态", minLen = 1, maxLen = 3, codeType = "PSN_INSU_STAS", regexpChinese = RegexpConst.REGEXP_CHINESE)
        private String psnInsuStas;
    
        /**
         * 人员编号
         */
        @ValiInfo(mean = "人员编号", minLen = 1, maxLen = 36, notBlank = true, regexpChinese = RegexpConst.REGEXP_CHINESE, illegalCharRegExp = RegexpConst.ILLEGAL_CHAR_REGEXP_PSNNO)
        private String psnNo;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    2、在代码中,通过调用valiObjStringField方法来进行校验:

    //control层的方法
    public ResultVO insertHmcYcx(@RequestBody HmcinfoDTO hmcinfoDTO){
        //.......其它逻辑
        
        //调用方法,进行自定义注解的校验
        String errorMsg = ToolUtils.valiObjStringField(hmcinfoDTO).toString();
        if (StringUtils.isNotBlank(errorMsg)) {
            log.info(errorMsg);
            return new ResultVO(errorMsg);
        }
        //.......其它逻辑
        ResultVO vo = hmcBPO.insertHmc(hmcinfoDTO);
        return vo;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    【智能优化算法】基于Jaya算法求解单目标优化问题附matlab代码MOJAYA
    【GCC编译优化系列】GCC链接失败的错误提示 undefined reference to ‘xxx‘ 可能还有一种情况你没注意到?
    mongodb.aggregate 索引查询+分组group+排序sort 优化查询效率
    计算机基础 --- 负数问题
    倍福Ethercat模块网络诊断和硬件排查的基本方法
    final/override 控制
    ribbonx编程笔记-读写注册表与使用自定义对话框
    JVM架构和内存管理优化
    【Linux】最新CentOS8内核升级
    NewStarCTF2023week3-Rabin‘s RSA
  • 原文地址:https://blog.csdn.net/m0_46459413/article/details/134257302