当前位置: 首页 > news >正文

【Java后端】SpringBoot 常用工具类和工具方法汇总

SpringBoot 项目里常见的 工具类(utils) 其实分三类:

  1. Spring 自带的工具类org.springframework.util.*

  2. Apache Commons / Google Guava 等常用工具类(在 SpringBoot 项目里经常配合使用)

  3. 业务中常见的自定义工具类(时间、JSON、加解密等)

下面整理一个 SpringBoot 常用 utils 工具类和常用方法清单


一、Spring 自带的工具类(常用在 SpringBoot 中)

这些类大部分在 org.springframework.util 包下。

1. 字符串工具类

  • StringUtils

    • StringUtils.hasText(str):是否有非空白字符

    • StringUtils.hasLength(str):是否非 null 且长度大于 0

    • StringUtils.isEmpty(str):是否为 null 或空串

    • StringUtils.collectionToDelimitedString(list, ","):集合转逗号分隔字符串

    • StringUtils.tokenizeToStringArray(str, ","):分割字符串


2. 集合工具类

  • CollectionUtils

    • CollectionUtils.isEmpty(list):判断集合是否为空

    • CollectionUtils.arrayToList(array):数组转 List

    • CollectionUtils.mergeArrayIntoCollection(array, collection):合并数组到集合

  • ObjectUtils

    • ObjectUtils.isEmpty(obj):判断对象是否为空(支持数组、集合、Map)

    • ObjectUtils.nullSafeEquals(a, b):安全比较两个对象


3. Assert 断言工具类

  • Assert

    • Assert.notNull(obj, "xxx不能为空")

    • Assert.hasText(str, "字符串不能为空")

    • Assert.isTrue(flag, "条件不满足")
      👉 常用于参数校验,避免手写 if (...) throw ...


4. 资源 & IO 工具类

  • FileCopyUtils

    • FileCopyUtils.copyToByteArray(inputStream):复制流到字节数组

    • FileCopyUtils.copy(inputStream, outputStream):流之间复制

  • StreamUtils

    • StreamUtils.copyToString(inputStream, Charset):把 InputStream 转成 String

  • ResourceUtils

    • ResourceUtils.getFile("classpath:config.yml"):获取资源文件


5. Bean 相关工具类

  • BeanUtils

    • BeanUtils.copyProperties(source, target):复制属性(常用 DTO -> Entity)

    • BeanUtils.instantiateClass(clazz):实例化对象

  • ReflectionUtils

    • ReflectionUtils.doWithFields(clazz, fieldCallback):遍历类字段

    • ReflectionUtils.makeAccessible(field):设置反射可访问


6. 环境/配置工具

  • SystemPropertyUtils

    • SystemPropertyUtils.resolvePlaceholders("${java.home}"):解析占位符

  • AntPathMatcher

    • matcher.match("/api/**", "/api/user/1"):Ant 风格路径匹配


二、第三方常用工具类(在 SpringBoot 中广泛使用)

Apache Commons Lang

  • StringUtils.isBlank(str) / StringUtils.isNotBlank(str)

  • StringUtils.join(list, ",")

  • RandomStringUtils.randomAlphanumeric(8)

Apache Commons Collections

  • CollectionUtils.isEmpty(coll)

  • CollectionUtils.union(a, b)

Google Guava

  • Lists.newArrayList()

  • Maps.newHashMap()

  • Strings.isNullOrEmpty(str)


三、业务常见自定义工具类

在实际 SpringBoot 项目里,经常会自己封装工具类,例如:

  1. DateTimeUtil

    • 格式化、解析日期(基于 java.time

    • LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))

  2. JsonUtil(通常封装 Jackson)

    • toJson(obj) → String

    • fromJson(json, clazz) → 对象

  3. ResponseUtil

    • 统一返回结果 Result.success(data) / Result.fail("错误")

  4. EncryptUtil

    • MD5、SHA256、AES、RSA 等加解密

  5. IdUtil

    • 生成 UUID、雪花算法 ID


✅ 总结:
SpringBoot 项目里最常用的工具类主要是 Spring 自带的 StringUtilsCollectionUtilsObjectUtilsAssertBeanUtils 等;
然后结合 Apache Commons / Guava 来增强;最后根据业务写一些 时间/JSON/加解密 工具类。


整理一个 SpringBoot 常用工具类速查表(CheatSheet),里面包含 Spring 自带 + 常用三方工具 + 业务自定义常见工具,并给上示例代码。


🚀 SpringBoot 常用 Utils 工具类速查表

1. 字符串工具类

工具类方法示例
org.springframework.util.StringUtilshasText(str)StringUtils.hasText("abc") → true
isEmpty(str)StringUtils.isEmpty("") → true
collectionToDelimitedString(list, ",")→ "a,b,c"
Apache Commons StringUtilsisBlank(str)StringUtils.isBlank(" ") → true
join(list, ",")→ "1,2,3"
Guava StringsisNullOrEmpty(str)Strings.isNullOrEmpty("") → true

2. 集合工具类

工具类方法示例
CollectionUtils (Spring)isEmpty(list)CollectionUtils.isEmpty(new ArrayList<>()) → true
arrayToList(array)→ [1, 2, 3]
Apache Commons CollectionUtilsunion(a, b)→ A ∪ B
Guava ListsnewArrayList("a","b")快速构建 List
Guava MapsnewHashMap()快速构建 Map

3. 对象工具类

工具类方法示例
ObjectUtils (Spring)isEmpty(obj)ObjectUtils.isEmpty(new int[]{}) → true
nullSafeEquals(a,b)ObjectUtils.nullSafeEquals("a","a") → true

4. Bean 工具类

工具类方法示例
BeanUtils (Spring)copyProperties(src, target)DTO → Entity 拷贝
ReflectionUtilsdoWithFields(clazz, callback)遍历字段,常用于注解处理

5. 参数校验工具类

工具类方法示例
Assert (Spring)notNull(obj, "不能为空")如果 obj==null 抛异常
hasText(str, "不能为空")如果为空字符串抛异常

6. 文件 & IO 工具类

工具类方法示例
FileCopyUtils (Spring)copyToByteArray(is)InputStream → byte[]
StreamUtilscopyToString(is, Charset)InputStream → String
ResourceUtilsgetFile("classpath:config.yml")获取资源文件

7. 路径 & 表达式工具

工具类方法示例
AntPathMatchermatch("/api/**", "/api/user/1")返回 true
SystemPropertyUtilsresolvePlaceholders("${java.home}")解析系统变量

8. 业务常见自定义工具类

工具类常用方法示例
DateTimeUtilformat(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss")→ "2025-09-23 15:30:00"
JsonUtil (封装 Jackson)toJson(obj) / fromJson(str, clazz)对象 ↔ JSON
ResponseUtilsuccess(data) / fail(msg)统一返回结果
EncryptUtilmd5(str) / aesEncrypt(text,key)加密解密
IdUtiluuid() / snowflakeId()唯一 ID 生成

http://www.dtcms.com/a/398514.html

相关文章:

  • leetcode hot100 中等难度 day03-刷题
  • Android | 使用 dumpsys alarm 验证自己应用使用的 Alarm 是否正确
  • React 展示Markdown内容
  • 营销型网站标准网页源码江西旺达建设工程有限公司网站
  • 南昌网站建设公司咨询交通局网站建设方案策划书
  • 阅读:Agent AI:Surveying the Horizons of Multimodal Interaction (2.2.1-2.2.3)
  • 提升网站建设品质福建省建设厅网站林瑞良
  • 阿里云网站建设服务费会计科目农产品网站建设投标书
  • 「企业模糊查询搜索api接口」详细介绍及调用使用方法
  • 【一天一个Web3概念】深入解析Web3空投:类型、参与策略与安全指南
  • JS逆向-Sign签名绕过技术算法可逆替换库模拟发包堆栈定位特征搜索安全影响
  • 网站一起做网店美工做兼职在那个网站
  • CI/CD Pipeline:完整指南
  • go引入自定义mod
  • 做网站需要多长时间iis 配置网站详解
  • 【Android】解决安卓在隐藏系统栏后usb鼠标被隐藏的问题
  • 公司企业网站免费建设长沙市天心区建设局网站
  • VS Code 格式化配置优先级与作用机制(包含ESLint)
  • IP地址的分类方法
  • 【halcon】新版 HALCON 中 `flush_graphic` 的正确打开方式
  • 数据科学-损失函数
  • Linux中mysql修改系统时间为北京时间,并修改成24h制,第275章
  • 网络通讯篇防火墙组策略入站和出站规则单层双层C2正反向上线解决方案
  • 【力扣LeetCode】 1413_逐步求和得到正数的最小值
  • 给别人做网站赚钱吗wordpress邮件找客户端
  • 有没有做logo的网站网站开发常去的论坛
  • todesk连接Mac设备时卡在100%(手机、平板连接时卡在75%)
  • ETF网格策略的呼吸机制基于市场热度的动态间距调控
  • 高性能服务器配置经验指南7——基于tar命令打包存储conda虚拟环境
  • C++ constexpr 修饰符与函数