定义注解
package com.zygh.investigation.control.common.excel.annotations;
import java.lang.annotation.*;
/**
* 字典格式化
*
* 实现将字典数据的值,格式化成字典数据的标签
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface DictFormat {
/**
* 例如说,SysDictTypeConstants、InfDictTypeConstants
*
* @return 字典类型
*/
String value();
}
使用注解
@TableName(value ="vehicle_list")
@Data
public class VehicleList implements Serializable {
@Schema(description = "限制区域")
@TableField(value = "limit_zone")
@DictFormat(DictTypeConstants.DISTRICT)
@ExcelProperty(value = {"行政区域"}, converter = DictConvert.class)
private String limitZone;
}
package com.zygh.investigation.control.common;
/**
* System 字典类型的枚举类
*
* @author zygh
*/
public interface DictTypeConstants {
String VEHICLE_TYPE = "vehicle_type";
}
解析注解
/**
* Excel 数据字典转换器
*
* @author zygh
*/
@Slf4j
public class DictConvert implements Converter<Object> {
@Override
public Object convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
// 使用字典解析
String type = getType(contentProperty);
String label = readCellData.getStringValue();
String value = DictFrameworkUtils.remoteDictDataValue(type, label);
if (value == null) {
log.error("[convertToJavaData][type({}) 解析不掉 label({})]", type, label);
return null;
}
// 将 String 的 value 转换成对应的属性
Class<?> fieldClazz = contentProperty.getField().getType();
return Convert.convert(fieldClazz, value);
}
private static String getType(ExcelContentProperty contentProperty) {
return contentProperty.getField().getAnnotation(DictFormat.class).value();
}
}
使用注解作用(根据字典类型(dict_type)与字典标签(label)获取字典值(value))
/**
* 字典工具类
*
* @author zygh
*/
@Slf4j
public class DictFrameworkUtils {
private static String BASE_URL;
@Value("${oauth2.base.url}")
public void setBaseUrl(String url) {
DictFrameworkUtils.BASE_URL = url;
}
public static String remoteDictDataValue(String dictType, String label) {
HashMap<String, Object> paramMap = new HashMap<>(8);
paramMap.put("dictType", dictType);
paramMap.put("label", label);
String result = HttpUtil.get(BASE_URL + "/admin-api/system/dict-data/parse/label", paramMap);
String res = null;
if(!StrUtil.isEmpty(result)) {
JSONObject jsonObject = JSONUtil.parseObj(result);
res = jsonObject.get("value").toString();
}
return res;
}
}