97 lines
3.4 KiB
Java
97 lines
3.4 KiB
Java
package com.ruoyi.aspect;
|
||
|
||
import cn.hutool.core.collection.CollUtil;
|
||
import cn.hutool.core.util.ReflectUtil;
|
||
import cn.hutool.core.util.StrUtil;
|
||
import com.ruoyi.cache.DictCache;
|
||
import com.ruoyi.common.exception.ServiceException;
|
||
import com.ruoyi.common.utils.bean.BeanValidators;
|
||
import lombok.RequiredArgsConstructor;
|
||
import org.aspectj.lang.ProceedingJoinPoint;
|
||
import org.aspectj.lang.annotation.Around;
|
||
import org.aspectj.lang.annotation.Aspect;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
import javax.validation.Validator;
|
||
import java.lang.reflect.Field;
|
||
import java.util.List;
|
||
|
||
@Aspect
|
||
@Component
|
||
@RequiredArgsConstructor
|
||
public class ImportAspect {
|
||
protected final Validator validator;
|
||
|
||
@Around("execution(* com.ruoyi.database.service.*.*import*(..))")
|
||
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
||
// 获取方法的入参
|
||
Object[] args = joinPoint.getArgs();
|
||
List<?> importList = (List<?>) args[0];
|
||
|
||
|
||
if (CollUtil.isEmpty(importList)) {
|
||
throw new ServiceException("导入数据为空");
|
||
}
|
||
|
||
// 获取list表中类的类型
|
||
Class<?> clazz = importList.get(0).getClass();
|
||
|
||
// 错误标记,判断是否有错误信息
|
||
boolean errorFlag = false;
|
||
// 遍历list表中的数据,回填字典值
|
||
for (Object obj : importList) {
|
||
|
||
// 记录属性中存在区域编码相关的属性的个数,判断如何回填区域编码
|
||
int codeCount = 0;
|
||
// 获取类中的所有属性
|
||
for (Field field : clazz.getDeclaredFields()) {
|
||
// 判断属性中是否有Cn结尾的属性
|
||
String fieldName = field.getName();
|
||
if (StrUtil.endWithIgnoreCase(fieldName, "Cn") && !field.getName().equals("structuredCameraTypeCn")) {
|
||
field.setAccessible(true);
|
||
// 获取非Cn属性名
|
||
String fieldName1 = StrUtil.subBefore(fieldName, "Cn", true);
|
||
String dictType = StrUtil.toUnderlineCase(fieldName1);
|
||
// 获取字典标签
|
||
Object dictLabel = field.get(obj);
|
||
int dictValue;
|
||
try {
|
||
// 获取字典值
|
||
dictValue = Integer.parseInt(DictCache.getDictValue(StrUtil.format("{}-{}", dictType, dictLabel)));
|
||
} catch (Exception e) {
|
||
// 字典值不存在,跳过
|
||
continue;
|
||
}
|
||
// 回填字典值
|
||
ReflectUtil.setFieldValue(obj, fieldName1, dictValue);
|
||
}
|
||
|
||
|
||
// // 判断属性中是否存在区域编码相关的属性
|
||
// if (StrUtil.equalsAny(fieldName, "placeCode", "gridCode", "buildingCode", "unitCode", "homeCode")) {
|
||
// codeCount++;
|
||
// }
|
||
|
||
|
||
}
|
||
|
||
// 校验数据,校验不通过则记录错误信息
|
||
try {
|
||
BeanValidators.validateWithException(validator, obj);
|
||
} catch (Exception e) {
|
||
ReflectUtil.setFieldValue(obj, "remark", e.getMessage());
|
||
errorFlag = true;
|
||
continue;
|
||
}
|
||
|
||
}
|
||
|
||
if (errorFlag) {
|
||
return importList;
|
||
}
|
||
|
||
// 执行目标方法
|
||
return joinPoint.proceed();
|
||
}
|
||
}
|