自定义注解使用

1.自定义注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldConstraints {

    /**
     * 字段长度判断.
     * @return 返回限制长度.
     */
    int limitLen() default 50;

    /**
     * 是否必填判断.
     * @return 限制是否为空.
     */
    boolean isNotBlank() default false;

    /**
     * 是否必填判断.
     * @return 限制是否为空.
     */
    boolean isNotNull() default false;

    /**
     * @return
     */
    /* 规则校验类. */
    Class ruleValidate() default NoSuchValidateRule.class;

}

2.引入自定义注解

@Setter
@Getter
@ToString
public class RuleVo {

    /**
     * 调用测系统来源.
     */
    @FieldConstraints(limitLen = 50,isNotBlank = true,ruleValidate = IdSoaValidateRule.class)
    private String systemId;

    /**
     * 调用方
     */
    @FieldConstraints(limitLen = 50,isNotBlank = true)
    private String appKey;

    /**
     * 调用方
     */
    @FieldConstraints(limitLen = 50,isNotBlank = true, ruleValidate = CorValidateRule.class )
    private String pin;

    @FieldConstraints(limitLen = 5000,isNotBlank = true)
    private String mobile;

    @FieldConstraints(limitLen = 20,isNotBlank = true, ruleValidate = kuValidateRule.class)
    private String sku;

    /**
     * 用户的ip地址.
     */
    @FieldConstraints(limitLen = 30,isNotBlank = true)
    private String userIp;
}

3.传入对象根据注解校验

public <T>  void validateFieldInfo(T t) throws ParamErrorException {
        if (null == t) {
            throw new ParamErrorException("校验参数(validateFieldInfo)参数为空.");
        }
        Field[] fields = t.getClass().getDeclaredFields();
        if (null == fields) {
            log.error("校验参数(validateFieldInfo)请求实体参数为空.");
            throw new ParamErrorException("校验参数(validateFieldInfo)请求实体参数为空.");
        }
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                boolean ruleFlag = field.isAnnotationPresent(FieldConstraints.class);
                if (ruleFlag) {
                    FieldConstraints fieldRule = field.getAnnotation(FieldConstraints.class);
                    //本来是注解必填才可以处理下边的规则,但是有些情况是可以不填,但是填了必须填正确.
//                    if (!fieldRule.isBlank()) {
//                        continue;
//                    }
                    // 如果类型是String  如果type是类类型,则前面包含"class ",后面跟类名
                    if (field.getGenericType().toString().equals("class java.lang.String")) {
                        fetchStringField(field, fieldRule, t);
                    } else {
                        log.warn("入参属性值" + field.getName() + "未被处理.");
                    }
                }else{
                    log.debug("入参属性值" + field.getName() + "未被处理.");
                }
            } catch (Exception ex) {
                log.error("处理入参属性为:{}异常!{}", new Object[]{field.getName(), ex.getMessage()});
                throw new ParamErrorException("入参属性值" + field.getName() + "校验异常."+ex.getMessage(), ex);
            }
        }
    }

 

    private <T> void fetchStringField(Field field, FieldConstraints fieldRule, T t) throws Exception {
            String value = (String) field.get(t);
            if (fieldRule.isNotBlank() && StringUtil.isBlank(value)) {
                throw new ParamErrorException("入参属性值" + field.getName() + "不能为空.");
            }
            if (fieldRule.isNotNull() && null == value) {
                throw new ParamErrorException("入参属性值" + field.getName() + "不能为空.");
            }
            if ((fieldRule.isNotBlank() || fieldRule.isNotNull()) && value.length() > fieldRule.limitLen()) {
                throw new ParamErrorException("入参属性值" + field.getName() + "长度超限.value:" + value);
            }
            if (fieldRule.ruleValidate().getName().endsWith(NoSuchValidateRule.class.getName())) {
                return;
            }
            ValidateRule validateRule = (ValidateRule) SpringContextHolder.getBean(fieldRule.ruleValidate());
            validateRule.validateTByRule(value);
    }

 

posted @ 2019-06-19 17:27  鹏鹏程子  阅读(465)  评论(0编辑  收藏  举报