基於spring和swagger寫了個引數校驗的方法在此做個儲存

naiveteRakish發表於2020-09-30
package com.cscec.pms.safety.impl.facade.util;

import com.cscec.pms.safety.impl.exception.SafetyExceptionType;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.yyc.ycloud.base.support.utils.AssertUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CheckParams
 * @Description
 * @Author junqi
 * @Date 2020/9/23 16:04
 * @Version 1.0
 **/
public class CheckParamsUtil {

    private static final Cache<String, String> cache;
    private static final String EMPTY = "";
    private static final String SEGMENTATION = ".";
    private static final String REMINDER = "不能為空";

    static {
        cache = CacheBuilder.newBuilder()
                .expireAfterAccess(30, TimeUnit.MINUTES)
                .recordStats() //開啟統計資訊開關
                .maximumSize(64)
                .build();

    }

    public static void checkParam(Object param, String... ignoreFields)  {
        Class<?> classes = param.getClass();
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(classes);
        for (PropertyDescriptor targetPd : targetPds) {
            Method readMethod = targetPd.getReadMethod();
            if (Arrays.stream(ignoreFields).anyMatch(field -> targetPd.getName().equals(field)))
                continue;
            try {
                String message = cache.get(classes.getName() + SEGMENTATION + targetPd.getName(), () -> {
                    try {
                        ApiModelProperty annotation = classes.getDeclaredField(targetPd.getName()).getAnnotation(io.swagger.annotations.ApiModelProperty.class);
                        return annotation != null ? annotation.value() + REMINDER : EMPTY;
                    } catch (NoSuchFieldException e) {
                        return EMPTY;
                    }
                });
                Object o = readMethod.invoke(param);
                AssertUtils.notNull(o, SafetyExceptionType.PARAM_ERROR, message);
                if (o instanceof String)
                    AssertUtils.hasLength(o.toString(), SafetyExceptionType.PARAM_ERROR, message);
                if (o instanceof Collection)
                    AssertUtils.notEmpty((Collection<?>) o, SafetyExceptionType.PARAM_ERROR, message);
                if (o instanceof Map)
                    AssertUtils.notEmpty((Map<?, ?>) o, SafetyExceptionType.PARAM_ERROR, message);
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }

}

相關文章