【Spring Boot】2.1 BaseUtil 工具类

本文介绍了在Spring Boot项目中创建一个BaseUtil工具类的实践,用于存放常用的基础功能方法。这些方法通常具有较低的对外耦合度,且在多个项目中频繁使用。随着开发经验的积累,BaseUtil类会不断丰富。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为项目创建一个utils子包 用来保存一些工具类
最基础的,也就是一些自己日常用的基础小功能的收集整理而来的BaseUtil

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.core.Local;
import org.springframework.util.DigestUtils;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.zip.GZIPOutputStream;

/***
 * Author: YL.Lou
 * Class: StringUtil
 * Project: washes_base_backstage
 * Introduce: 处理字符串
 * DateTime: 2022-06-27 11:34
 ***/
@Slf4j
public class BaseUtil {

    /**
     * 获取当前时间的秒级时间戳
     * @return 秒级时间戳
     */
    public static Long getTimestamp(){
        return date2Timestamp(null, true);
    }

    /**
     * 日期字符串 转 Date
     * @param str 日期字符串 null 按当前时间戳
     * @return Date对象
     */
    public static Date str2Date(String str) throws ParseException {
        if (null == str){
            return new Date();
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
    }

    /**
     * 日期字符串 转 LocalDateTime
     * @param str 日期字符串 null 按当前时间戳
     * @return LocalDateTime 对象
     */
    public static LocalDateTime str2LocalDateTime(String str){
        if (null == str){
            return LocalDateTime.now();
        }
        return LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 时间戳 转 Date
     * @param timestamp 时间戳 null 按当前时间戳
     * @param isSecond true 入参为秒 false 入参为毫秒
     * @return Date对象
     */
    public static Date timestamp2Date(Long timestamp, boolean isSecond){
        if (null == timestamp){
            return new Date();
        }

        if (isSecond){
            timestamp = timestamp * 1000;
        }

        return new Date(timestamp);
    }

    /**
     * 时间戳 转 LocalDateTime
     * @param timestamp 时间戳 null 按当前时间
     * @param isSecond true 入参为秒 false 入参为毫秒
     * @return LocalDateTime 对象
     */
    public static LocalDateTime timestamp2LocalDateTime(Long timestamp, boolean isSecond){
        if(null == timestamp){
            return LocalDateTime.now();
        }

        if (isSecond){
            timestamp = timestamp * 1000;
        }

        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("+8"));
    }

    /**
     * Date 转 日期字符串
     * @param date Date对象 null 按当前时间戳
     * @return 字符串
     */
    public static String date2String(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (null == date){
            return simpleDateFormat.format(new Date());
        }

        return simpleDateFormat.format(date);
    }

    /**
     * Date 转 时间戳
     * @param date Date对象 null 按当前时间戳
     * @param isSecond true 出参为秒 false 出参为毫秒
     * @return 时间戳
     */
    public static Long date2Timestamp(Date date, boolean isSecond){
        if (null == date){
            return new Date().getTime();
        }

        if (isSecond){
            return date.getTime() / 1000;
        }

        return date.getTime();
    }

    /**
     * LocalDateTime 转 日期字符串
     * @param local LocalDateTime 对象 null 按当前时间戳
     * @return 日期字符串
     */
    public static String localDateTime2String(LocalDateTime local){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        if (null == local){
            return dateTimeFormatter.format(LocalDateTime.now());
        }

        return dateTimeFormatter.format(local);
    }

    /**
     * LocalDateTime 转 时间戳
     * @param local LocalDateTime 对象 null 按当前时间戳
     * @param isSecond true 出参为秒 false 出参为毫秒
     * @return 时间戳
     */
    public static Long localDateTime2Timestamp(LocalDateTime local, boolean isSecond){
        if (isSecond){
            return LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000;
        }
        return LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 返回MD5加密后的字符串
     * @param str
     * @return
     */
    public static String getMD5(String str){
        String s = DigestUtils.md5DigestAsHex(str.getBytes());
        return s;
    }

    /**
     * 返回随机字符串
     * @param length 需要返回的字符串长度
     * @return
     */
    public static String getRandom(Integer length){
        if (length == null){
            length = 6;
        }

        Random random = new Random();

        String str = "";
        for (int i = 0; i < length; i++) {
            int i1 = random.nextInt(9);
            if (i == 0 && i1 == 0){
                i1 = 1;
            }
            str += String.valueOf(i1);
        }

        return str;
    }

    /**
     * 返回指定区间的随机数字
     * @param min 最小值
     * @param max 最大值
     * @return
     */
    public static int getRandomNum(int min, int max){

        if ( max <= min){
            return max;
        }

        Random random = new Random();
        int i = min + random.nextInt(max - min);

        return i;
    }

    /**
     * 对字符进行GZIP压缩
     * @param str 要压缩的字符串
     * @return
     */
    public static String gzipString(String str){
        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gzipOut=new GZIPOutputStream(bos);
            gzipOut.write(str.getBytes(StandardCharsets.UTF_8));
            gzipOut.finish();
            gzipOut.close();
            String base64= Base64.getEncoder().encodeToString(bos.toByteArray());
            return base64;
        }catch(Exception e){
            e.printStackTrace();
            return str;
        }
    }

    /**
     * 实体类转 hashMap 并执行排序 自动忽略null值
     * @param entity 实体类
     * @return hashMap
     */
    public static Map<String, Object> entity2map(Object entity){
        // 定义一个Map
        Map<String, Object> map = new TreeMap<>();

        // 得到实体类的属性值
        Field[] fields = entity.getClass().getDeclaredFields();

        // 遍历属性值
        for (Field field: fields) {
            // 调整属性的可访问性
            field.setAccessible(true);

            // 获取属性名称
            String fieldName = field.getName();

            // 获取属性值
            Object fieldValue;
            try {
                fieldValue = field.get(entity);
            } catch (IllegalAccessException e) {
                fieldValue = null;
            }

            // 判断属性值是否为Null
            if (null == fieldValue){
                continue;
            }

            // 将有效值放入Map
            map.put(fieldName,fieldValue);
        }

        return map;
    }

    /**
     * 判断是否为基本类型的默认值
     * @param object
     * @return
     */
    public static boolean isBaseDefaultValue(Object object) {
        Class className = object.getClass();
        return className.equals(Integer.class)
                || className.equals(Byte.class)
                || className.equals(Long.class)
                || className.equals(Double.class)
                || className.equals(Float.class)
                || className.equals(Character.class)
                || className.equals(Short.class)
                || className.equals(Boolean.class)
                || className.equals(String.class);
    }
}

该类中的 方法通常是与外部耦合性较低的、使用频率较高的、随着开发项目增多而逐渐积累 而来的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值