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

SpringBoot常用内置工具类使用示例

工具类

以下是对这些 Spring 工具类的简要介绍,涵盖其核心功能和典型用途:

1. StringUtils

字符串处理工具类,提供判空(isEmpty)、集合转字符串(collectionToDelimitedString)、首字母大小写转换(capitalize)、去除空白(trimWhitespace)等常用操作,避免手动处理空指针和边界情况。

2. CollectionUtils

集合操作工具类,用于判断集合是否为空(isEmpty)、合并集合(mergeArrayIntoCollection)、判断子集关系(containsAny)等,简化集合处理逻辑,兼容各种集合类型(List、Set 等)。

3. ObjectUtils

通用对象处理工具类,提供对象判空(isEmpty,支持数组、集合等)、对象转字符串(nullSafeToString)、比较对象(nullSafeEquals)等功能,统一处理不同类型对象的空值和转换问题。

4. Assert

断言工具类,用于参数校验,如 notNull(非空校验)、isTrue(条件校验)、hasText(字符串非空且有内容)等,校验失败时抛出 IllegalArgumentException,简化参数合法性检查代码。

5. DigestUtils

消息摘要工具类,提供 MD5、SHA-1、SHA-256 等哈希算法的便捷实现(如 md5DigestAsHexsha256DigestAsHex),常用于密码加密、数据完整性校验等场景。

6. Base64Utils

Base64 编解码工具类,提供 encode(编码)和 decode(解码)方法,用于二进制数据与字符串的转换(如传输图片、文件等场景),基于 JDK 实现但简化了调用方式。

7. StopWatch

计时工具类,用于统计代码片段的执行时间,支持多任务计时(start/stop)、总时间计算(getTotalTimeMillis)和任务详情展示(prettyPrint),方便性能分析和代码优化。

8. AntPathMatcher

Ant 风格路径匹配工具类,支持 *(单级路径)和 **(多级路径)通配符,用于路径匹配(如 match 方法)和变量提取(extractUriTemplateVariables),常见于 Spring MVC 路由匹配、权限路径校验等场景。

9. ReflectionUtils

反射工具类,简化反射操作,如查找方法(findMethod)、调用方法(invokeMethod)、访问字段(findField/getField)等,自动处理访问权限(makeAccessible),避免手动处理 NoSuchMethodException 等异常。

10. LinkedMultiValueMap

支持多值的 Map 实现,键可以对应多个值且保持插入顺序,提供 add(添加值)、set(替换值)等方法,常用于 HTTP 请求参数、响应头存储(一个键对应多个值的场景)。

11. FileCopyUtils

文件复制工具类,提供文件到文件(copy(File, File))、流到流(copy(InputStream, OutputStream))、内容到文件(copy(byte[], File))等复制操作,自动处理流的关闭,简化 IO 操作。

12. StreamUtils

流操作工具类,用于流的复制(copy(InputStream, OutputStream))、流转字符串(copyToString)等,支持指定字符集,避免手动处理流的读取和关闭逻辑。

13. ClassUtils

类操作工具类,提供获取类名(getShortName)、判断类是否存在(isPresent)、获取父类/接口(getAllInterfaces)等功能,常用于反射场景中的类信息解析。

14. NumberUtils

数字处理工具类,提供字符串转数字(parseNumber)、判断是否为有效数字(isCreatable)、数字范围校验等功能,简化类型转换和数字合法性检查。

15. UriComponentsBuilder

URI 构建工具类,用于拼接 URL 路径、查询参数(queryParam)、片段等,自动处理编码(如特殊字符转义),避免手动拼接 URI 导致的格式错误。

16. SystemPropertyUtils

系统属性解析工具类,用于解析包含系统属性占位符的字符串(如 ${user.home}),支持默认值(${key:default}),简化系统环境变量、配置参数的动态获取。

17. ResourceUtils

资源文件处理工具类,用于获取类路径下的资源(getFile("classpath:xxx"))、URL 资源等,自动处理不同资源路径(如类路径、文件系统路径)的解析,常用于加载配置文件。

测试用例

import org.junit.jupiter.api.Test;
import org.springframework.util.*;
import org.springframework.web.util.UriComponentsBuilder;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;import static org.junit.jupiter.api.Assertions.*;/*** @Author: hweiyu* @Description: TODO* @Date: 2025/10/21 9:14*/
public class SpringUtilTest {// 1. StringUtils 测试@Testvoid testStringUtils() {// 判空测试assertTrue(StringUtils.isEmpty(""));assertTrue(StringUtils.isEmpty(null));assertFalse(StringUtils.isEmpty("test"));// 集合转字符串String delimited = StringUtils.collectionToDelimitedString(Arrays.asList("a", "b"), ",");assertEquals("a,b", delimited);// 首字母大写assertEquals("Hello", StringUtils.capitalize("hello"));}// 2. CollectionUtils 测试@Testvoid testCollectionUtils() {List<String> emptyList = new ArrayList<>();assertTrue(CollectionUtils.isEmpty(emptyList));List<String> nonEmptyList = Arrays.asList("test");assertFalse(CollectionUtils.isEmpty(nonEmptyList));// 合并集合List<String> list1 = Arrays.asList("x", "y");List<String> list2 = Arrays.asList("z");List<String> merged = new ArrayList<>();CollectionUtils.mergeArrayIntoCollection(list1.toArray(), merged);CollectionUtils.mergeArrayIntoCollection(list2.toArray(), merged);assertEquals(Arrays.asList("x", "y", "z"), merged);}// 3. ObjectUtils 测试@Testvoid testObjectUtils() {Object nullObj = null;assertTrue(ObjectUtils.isEmpty(nullObj));Object strObj = "test";assertFalse(ObjectUtils.isEmpty(strObj));int[] emptyArr = {};assertTrue(ObjectUtils.isEmpty(emptyArr));// 数组转字符串String[] arr = {"a", "b"};assertEquals("{a, b}", ObjectUtils.nullSafeToString(arr));}// 4. Assert 测试@Testvoid testAssert() {// 测试非空断言assertDoesNotThrow(() -> Assert.notNull("value", "不应抛异常"));IllegalArgumentException notNullEx = assertThrows(IllegalArgumentException.class,() -> Assert.notNull(null, "参数为null"));assertEquals("参数为null", notNullEx.getMessage());// 测试条件断言assertDoesNotThrow(() -> Assert.isTrue(1 == 1, "条件成立"));IllegalArgumentException isTrueEx = assertThrows(IllegalArgumentException.class,() -> Assert.isTrue(1 > 2, "条件不成立"));assertEquals("条件不成立", isTrueEx.getMessage());}// 5. DigestUtils 测试@Testvoid testDigestUtils() {String content = "spring-digest";String md5 = DigestUtils.md5DigestAsHex(content.getBytes());assertEquals("fc792b0b3b7004c0afe818befe3c6892", md5);}// 6. Base64Utils 测试@Testvoid testBase64Utils() {String original = "spring-base64";byte[] encoded = Base64Utils.encode(original.getBytes());byte[] decoded = Base64Utils.decode(encoded);assertEquals(original, new String(decoded, StandardCharsets.UTF_8));}// 7. StopWatch 测试@Testvoid testStopWatch() throws InterruptedException {StopWatch watch = new StopWatch();watch.start("task1");Thread.sleep(100);watch.stop();watch.start("task2");Thread.sleep(200);watch.stop();assertEquals(2, watch.getTaskCount());assertTrue(watch.getTotalTimeMillis() >= 250); // 允许误差}// 8. AntPathMatcher 测试@Testvoid testAntPathMatcher() {AntPathMatcher matcher = new AntPathMatcher();assertTrue(matcher.match("/api/**", "/api/user/1"));assertFalse(matcher.match("/api/*", "/api/user/1"));assertEquals("1", matcher.extractUriTemplateVariables("/user/{id}", "/user/1").get("id"));}// 9. ReflectionUtils 测试@Testvoid testReflectionUtils() {// 测试调用方法Method lengthMethod = ReflectionUtils.findMethod(String.class, "length");Integer length = (Integer) ReflectionUtils.invokeMethod(lengthMethod, "test");assertEquals(4, length);// 测试访问字段TestEntity entity = new TestEntity("test-field");Field field = ReflectionUtils.findField(TestEntity.class, "field");ReflectionUtils.makeAccessible(field);String fieldValue = (String) ReflectionUtils.getField(field, entity);assertEquals("test-field", fieldValue);}// 10. LinkedMultiValueMap 测试@Testvoid testLinkedMultiValueMap() {LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();map.add("key", "val1");map.add("key", "val2");assertEquals(Arrays.asList("val1", "val2"), map.get("key"));map.set("key", "val3");assertEquals(Collections.singletonList("val3"), map.get("key"));}// 11. FileCopyUtils 测试@Testvoid testFileCopyUtils() throws IOException {File source = File.createTempFile("source", ".txt");File target = File.createTempFile("target", ".txt");FileCopyUtils.copy("temp content".getBytes(), source);FileCopyUtils.copy(source, target);byte[] content = FileCopyUtils.copyToByteArray(target);assertEquals("temp content", new String(content));// 清理临时文件source.deleteOnExit();target.deleteOnExit();}// 12. StreamUtils 测试@Testvoid testStreamUtils() throws IOException {ByteArrayInputStream in = new ByteArrayInputStream("stream test".getBytes());ByteArrayOutputStream out = new ByteArrayOutputStream();StreamUtils.copy(in, out);assertEquals("stream test", out.toString(StandardCharsets.UTF_8.name()));}// 13. ClassUtils 测试@Testvoid testClassUtils() {assertEquals("String", ClassUtils.getShortName(String.class));assertTrue(ClassUtils.isPresent("java.lang.Integer", null));assertFalse(ClassUtils.isPresent("com.unknown.Class", null));}// 14. NumberUtils 测试@Testvoid testNumberUtils() {Integer num = NumberUtils.parseNumber("123", Integer.class);assertEquals(123, num);}// 15. UriComponentsBuilder 测试@Testvoid testUriComponentsBuilder() {String uri = UriComponentsBuilder.fromUriString("http://example.com").path("/user").queryParam("id", 1).build().toUriString();assertEquals("http://example.com/user?id=1", uri);}// 内部辅助类(用于反射测试)static class TestEntity {private final String field;public TestEntity(String field) { this.field = field; }}// 补充:16. SystemPropertyUtils 测试@Testvoid testSystemPropertyUtils() {// 保存原始系统属性(避免影响其他测试)String originalProp = System.getProperty("test.system.prop");try {// 设置测试系统属性System.setProperty("test.system.prop", "expectedValue");// 测试解析系统属性占位符String resolved = SystemPropertyUtils.resolvePlaceholders("${test.system.prop}");assertEquals("expectedValue", resolved);// 测试默认值(当属性不存在时)String withDefault = SystemPropertyUtils.resolvePlaceholders("${unknown.prop:defaultVal}");assertEquals("defaultVal", withDefault);} finally {// 恢复原始属性if (originalProp == null) {System.clearProperty("test.system.prop");} else {System.setProperty("test.system.prop", originalProp);}}}// 补充:17. ResourceUtils 测试@Testvoid testResourceUtils() throws IOException {// 测试获取类路径下的资源(需确保项目根目录有该文件,或修改为实际存在的资源)// 常见场景:读取 src/test/resources 或 src/main/resources 下的文件File resourceFile = ResourceUtils.getFile("classpath:application.properties");assertTrue(resourceFile.exists(), "资源文件不存在,请确认classpath下是否有application.properties");// 测试URL格式的资源(如文件系统路径)File tempFile = File.createTempFile("test", ".txt");String fileUrl = "file:" + tempFile.getAbsolutePath();File urlFile = ResourceUtils.getFile(fileUrl);assertTrue(urlFile.exists());tempFile.deleteOnExit(); // 清理临时文件}
}
http://www.dtcms.com/a/511379.html

相关文章:

  • Qt和ffmpeg结合打造gb28181推流/支持udp和tcp被动以及tcp主动三种方式
  • 设计模式-工厂模式:解耦对象创建的设计艺术
  • UVa 1660 Cable TV Network
  • 使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
  • 网站建设年度计划申请了域名 网站怎么建设呢
  • 《黄雀》电视剧总结
  • 云计算与服务器概述
  • 【Java Web学习 | 第1篇】前端 - HTML
  • Jenkins流水线项目发布
  • 网站优化需要做什么烟台网站建设比较大的
  • CAN入侵检测系统IDS不行,用扩充白名单机制保证汽车功能安全需求
  • 微软Teams的Media bypass的介绍
  • 分布式一致性
  • 使用微软Agent Framework .NET构建智能代理应用
  • MOSHELL (10) : COLI 交互
  • 九江网站开发wordpress适合seo
  • 【JavaScript】some方法的详解与实战
  • 买机票便宜网站建设分站式二手车网站源码
  • windows配置hadoop环境
  • Java中的单例模式
  • K8s部署,新版本
  • LXC容器操作实战【Linux】
  • CAN总线: 仲裁
  • ⸢ 捌-Ⅱ⸥⤳ 可信纵深防御应用实践:软件供应链、数据滥用、安全加固
  • Linux Bash(二)
  • 上海建设单位工程备案网站宜宾网站建设网站
  • AI: 生成Android自我学习路线规划与实战
  • 项目实践2—全球证件智能识别系统(Qt客户端开发+FastAPI后端人工智能服务开发)
  • 百度面试题解析:新生代分区、垃圾回收算法、虚拟机栈和类加载(四)
  • AIDC爆火,储能企业跨界抢滩AI能源“新战场”