java注解使用

定义注解

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;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值