首頁  >  文章  >  Java  >  怎麼使用Springboot封裝一個自適配的資料單位轉換工具類

怎麼使用Springboot封裝一個自適配的資料單位轉換工具類

WBOY
WBOY轉載
2023-05-11 22:34:14991瀏覽

    前言

    平時做一些統計數據,經常從資料庫或從介面取得出來的數據,單位是跟業務需求不一致的。

    例如, 我們拿出來的, 其實要是

    又比如,我們拿到的資料需要乘以100 返回給前端做百分比展示

    又比如, 千分比轉換

    又比如,拿出來的金額需要變成萬為單位

    又比如,需要保留2位元小數

    ......

    等等等等。

    平常我們要怎麼搞?

    很多時候拿到的是一個資料集合list,就需要去遍歷然後根據每個DTO的屬性去做相關單位轉換。

    一直get 完 set ,get 完 set ,get 完 set ,get 完 set ,get 完 set ,人都麻了。

    就像這樣:

    怎麼使用Springboot封裝一個自適配的資料單位轉換工具類

    所以,如果透過反射自動匹配出來一些操作轉換,是不是就看程式碼看起來舒服一點,人也輕鬆一點。

    答案: 是的

    然後,我就搞了。

    本篇內容簡要:

    ① 初步的封裝,透過map去標記需要轉換的類別屬性欄位

    ##② 進一步的封裝, 配合老朋友自訂註解搞事情

    產品:

    支付總金額換成萬為單位,方便營運統計;

    那個什麼計數,要是百分比的;

    然後還有一個是千分比;

    另外,還有2個要保留2位小數;

    還有啊,那個。 。 。 。 。 。


    我:

    別說了,喝著口水吧。

    得到的資料都在這個DTO裡面:

    怎麼使用Springboot封裝一個自適配的資料單位轉換工具類

    #開始封裝:

    ① 初步的封裝,透過map去標記需要轉換的類別屬性欄位

    思路玩法: 

    a.透過反射拿出欄位

    b.配合傳入的轉換標記Map 符合哪些欄位需要操作

    c.然後從map取出相關字段的具體操作是什麼,然後執行轉換操作

    d.重新賦值 

    ① 簡單弄個枚舉,列出現在需求上的轉換操作類型

    UnitConvertType.java

    /**
     * @Author : JCccc
     * @CreateTime : 2023/01/14
     * @Description :
     **/
    public enum UnitConvertType {
     
        /**
         * 精度
         */
        R,
        /**
         * 万元
         */
        B,
        /**
         * 百分
         */
        PERCENTAGE,
        /**
         * 千分
         */
        PERMIL
    }

    ② 核心封裝的轉換函數 

    UnitConvertUtil.java

    import lombok.extern.slf4j.Slf4j;
    import java.lang.reflect.Field;
    import java.math.BigDecimal;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
     
    /**
     * @Author : JCccc
     * @CreateTime : 2023/01/14
     * @Description :
     **/
    @Slf4j
    public class UnitConvertUtil {
     
        public static <T> void unitMapConvert(List<T> list, Map<String, UnitConvertType> propertyMap) {
            for (T t : list) {
                Field[] declaredFields = t.getClass().getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    if (propertyMap.keySet().stream().anyMatch(x -> x.equals(declaredField.getName()))) {
                        try {
                            declaredField.setAccessible(true);
                            Object o = declaredField.get(t);
                            UnitConvertType unitConvertType = propertyMap.get(declaredField.getName());
                            if (o != null) {
                                if (unitConvertType.equals(UnitConvertType.PERCENTAGE)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                                if (unitConvertType.equals(UnitConvertType.PERMIL)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                                if (unitConvertType.equals(UnitConvertType.B)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                                if (unitConvertType.equals(UnitConvertType.R)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                            }
                        } catch (Exception ex) {
                            log.error("处理失败");
                            continue;
                        }
     
                    }
                }
            }
        }
        
        public static void main(String[] args) {
     
            //获取模拟数据
            List<MySumReportDTO> list = getMySumReportList();
     
            Map<String, UnitConvertType> map =new HashMap<>();
            map.put("payTotalAmount", UnitConvertType.B);
            map.put("jcAmountPercentage", UnitConvertType.PERCENTAGE);
            map.put("jcCountPermillage", UnitConvertType.PERMIL);
            map.put("length", UnitConvertType.R);
            map.put("width", UnitConvertType.R);
            unitMapConvert(list,map);
            System.out.println("通过map标识的自动转换玩法:"+list.toString());
     
        }
     
        private static List<MySumReportDTO> getMySumReportList() {
            MySumReportDTO mySumReportDTO = new MySumReportDTO();
            mySumReportDTO.setPayTotalAmount(new BigDecimal(1100000));
            mySumReportDTO.setJcAmountPercentage(BigDecimal.valueOf(0.695));
            mySumReportDTO.setJcCountPermillage(BigDecimal.valueOf(0.7894));
            mySumReportDTO.setLength(BigDecimal.valueOf(1300.65112));
            mySumReportDTO.setWidth(BigDecimal.valueOf(6522.12344));
     
            MySumReportDTO mySumReportDTO1 = new MySumReportDTO();
            mySumReportDTO1.setPayTotalAmount(new BigDecimal(2390000));
            mySumReportDTO1.setJcAmountPercentage(BigDecimal.valueOf(0.885));
            mySumReportDTO1.setJcCountPermillage(BigDecimal.valueOf(0.2394));
            mySumReportDTO1.setLength(BigDecimal.valueOf(1700.64003));
            mySumReportDTO1.setWidth(BigDecimal.valueOf(7522.12344));
     
            List<MySumReportDTO> list = new ArrayList<>();
     
            list.add(mySumReportDTO);
            list.add(mySumReportDTO1);
            return list;
        }
    }

    程式碼簡析: 

    UnitConvertUtil.java

    public static void main(String[] args) {
    
        //获取模拟数据
        List<MySumReportDTO> list = getMySumReportList();
        System.out.println("转换前:"+list.toString());
        Map<String, UnitConvertType> map =new HashMap<>();
        map.put("payTotalAmount", UnitConvertType.B);
        map.put("jcAmountPercentage", UnitConvertType.PERCENTAGE);
        map.put("jcCountPermillage", UnitConvertType.PERMIL);
        map.put("length", UnitConvertType.R);
        map.put("width", UnitConvertType.R);
        unitMapConvert(list,map);
        System.out.println("通过map标识的自动转换玩法:"+list.toString());
    }

    程式碼簡析: 怎麼使用Springboot封裝一個自適配的資料單位轉換工具類UnitConvertUtil.java

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
     
    /**
     * @Author : JCccc
     * @CreateTime : 2023/01/14
     * @Description :
     **/
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface JcBigDecConvert {
     
        UnitConvertType name();
    }

    程式碼簡析: 

    怎麼使用Springboot封裝一個自適配的資料單位轉換工具類看看怎麼呼叫的:

    import lombok.Data;
    import java.io.Serializable;
    import java.math.BigDecimal;
     
    /**
     * @Author : JCccc
     * @CreateTime : 2023/2/03
     * @Description :
     **/
     
    @Data
    public class MyYearSumReportDTO implements Serializable {
        private static final long serialVersionUID = 5285987517581372888L;
     
        //支付总金额
        @JcBigDecConvert(name=UnitConvertType.B)
        private BigDecimal payTotalAmount;
     
        //jc金额百分比
        @JcBigDecConvert(name=UnitConvertType.PERCENTAGE)
        private BigDecimal jcAmountPercentage;
     
        //jc计数千分比
        @JcBigDecConvert(name=UnitConvertType.PERMIL)
        private BigDecimal jcCountPermillage;
     
        //保留2位
        @JcBigDecConvert(name=UnitConvertType.R)
        private BigDecimal length;
     
        //保留2位
        @JcBigDecConvert(name=UnitConvertType.R)
        private BigDecimal width;
    }

    程式碼簡析: 

    怎麼使用Springboot封裝一個自適配的資料單位轉換工具類

    效果:

    怎麼使用Springboot封裝一個自適配的資料單位轉換工具類

    整個集合list的對應欄位都會自動轉換成功(轉換邏輯想怎麼樣就自己在對應if裡面調整、拓展): 

    ② 進一步的封裝, 配合老朋友自訂註解搞事情

    實說實話,第一步的封裝程度已經夠用了,就是傳map標識出來哪些需要轉換,對應轉換列舉類型是什麼。

    其實我覺得是夠用的。

    但是麼,為了用起來更加方便,或者說 更加可拓展, 那麼配合自訂註解是更nice的。

    開搞。

    建立一個自訂註解 ,JcBigDecConvert.java

        public static <T> void unitAnnotateConvert(List<T> list) {
            for (T t : list) {
                Field[] declaredFields = t.getClass().getDeclaredFields();
                for (Field declaredField : declaredFields) {
                        try {
                            if (declaredField.getName().equals("serialVersionUID")){
                                continue;
                            }
                            JcBigDecConvert myFieldAnn = declaredField.getAnnotation(JcBigDecConvert.class);
                            if(Objects.isNull(myFieldAnn)){
                                continue;
                            }
                            UnitConvertType unitConvertType = myFieldAnn.name();
                            declaredField.setAccessible(true);
                            Object o = declaredField.get(t);
                            if (Objects.nonNull(o)) {
                                if (unitConvertType.equals(UnitConvertType.PERCENTAGE)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                                if (unitConvertType.equals(UnitConvertType.PERMIL)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                                if (unitConvertType.equals(UnitConvertType.B)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                                if (unitConvertType.equals(UnitConvertType.R)) {
                                    BigDecimal bigDecimal = ((BigDecimal) o).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    declaredField.set(t, bigDecimal);
                                }
                            }
                        } catch (Exception ex) {
                            log.error("处理失败");
                        }
                }
            }
        }

    怎麼用?就是在我們的報表DTO裡面,去標記欄位。

    範例:

    MyYearSumReportDTO.java

    怎麼使用Springboot封裝一個自適配的資料單位轉換工具類ps: 可以看到我們在欄位上面使用了自訂註解

        public static void main(String[] args) {
            
            List<MyYearSumReportDTO> yearsList = getMyYearSumReportList();
            unitAnnotateConvert(yearsList);
            System.out.println("通过注解标识的自动转换玩法:"+yearsList.toString());
        }
        
        private static List<MyYearSumReportDTO> getMyYearSumReportList() {
            MyYearSumReportDTO mySumReportDTO = new MyYearSumReportDTO();
            mySumReportDTO.setPayTotalAmount(new BigDecimal(1100000));
            mySumReportDTO.setJcAmountPercentage(BigDecimal.valueOf(0.695));
            mySumReportDTO.setJcCountPermillage(BigDecimal.valueOf(0.7894));
            mySumReportDTO.setLength(BigDecimal.valueOf(1300.65112));
            mySumReportDTO.setWidth(BigDecimal.valueOf(6522.12344));
            MyYearSumReportDTO mySumReportDTO1 = new MyYearSumReportDTO();
            mySumReportDTO1.setPayTotalAmount(new BigDecimal(2390000));
            mySumReportDTO1.setJcAmountPercentage(BigDecimal.valueOf(0.885));
            mySumReportDTO1.setJcCountPermillage(BigDecimal.valueOf(0.2394));
            mySumReportDTO1.setLength(BigDecimal.valueOf(1700.64003));
            mySumReportDTO1.setWidth(BigDecimal.valueOf(7522.12344));
            
            List<MyYearSumReportDTO> list = new ArrayList<>();
            list.add(mySumReportDTO);
            list.add(mySumReportDTO1);
            return list;
        }

    然後針對配合我們的自定義,封一個轉換函數,反射取得屬性字段,然後解析註解,然後做對應轉換操作。

     程式碼:

    rrreee怎麼使用Springboot封裝一個自適配的資料單位轉換工具類寫個呼叫範例看看效果:

    rrreee###效果也是很OK:###### ######

    以上是怎麼使用Springboot封裝一個自適配的資料單位轉換工具類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除