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);
}
}
}
}
基于spring和swagger写了个参数校验的方法在此做个保存
最新推荐文章于 2024-06-27 20:12:16 发布