SpringBoot中内置常用工具类(springboot工具类读取配置文件)
zhezhongyun 2025-07-24 23:18 6 浏览
前言:
SpringBoot以其强大的自动配置和丰富的生态系统成为Java开发的首选框架。除了核心功能外,SpringBoot及其依赖的Spring框架还包含大量实用工具类,它们可以显著简化日常开发工作。本文将介绍几个用工具类,并通过简洁的代码示例展示它们的基本用法。
字符串处理工具类
1.StringUtils
import org.springframework.util.StringUtils;
// 检查字符串是否为空
boolean isEmpty = StringUtils.isEmpty(null); // true
boolean isEmpty2 = StringUtils.isEmpty(""); // true
// 检查字符串是否有文本内容
boolean hasText = StringUtils.hasText(" "); // false
boolean hasText2 = StringUtils.hasText("hello"); // true
// 分割字符串
String[] parts = StringUtils.tokenizeToStringArray("a,b,c", ",");
// 清除首尾空白
String trimmed = StringUtils.trimWhitespace(" hello "); // "hello"
2.AntPathMatcher
import org.springframework.util.AntPathMatcher;
AntPathMatcher matcher = new AntPathMatcher();
boolean match1 = matcher.match("/users/*", "/users/123"); // true
boolean match2 = matcher.match("/users/**", "/users/123/orders"); // true
boolean match3 = matcher.match("/user?", "/user1"); // true
// 提取路径变量
Map<String, String> vars = matcher.extractUriTemplateVariables("/users/{id}", "/users/42"); // {id=42}
3. PatternMatchUtils
import org.springframework.util.PatternMatchUtils;
boolean matches1 = PatternMatchUtils.simpleMatch("user*", "username"); // true
boolean matches2 = PatternMatchUtils.simpleMatch("user?", "user1"); // true
boolean matches3 = PatternMatchUtils.simpleMatch(new String[]{"user*", "admin*"}, "username"); // true
集合和数组工具类
4. CollectionUtils
import org.springframework.util.CollectionUtils;
// 检查集合是否为空
boolean isEmpty = CollectionUtils.isEmpty(null); // true
boolean isEmpty2 = CollectionUtils.isEmpty(Collections.emptyList()); // true
// 集合操作
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("b", "c", "d");
Collection<String> intersection = CollectionUtils.intersection(list1, list2); // [b, c]
// 合并集合
List<String> target = new ArrayList<>();
CollectionUtils.mergeArrayIntoCollection(new String[]{"a", "b"}, target);
5. MultiValueMap
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("colors", "red");
map.add("colors", "blue");
map.add("sizes", "large");
List<String> colors = map.get("colors"); // [red, blue]
6. ConcurrentReferenceHashMap
import org.springframework.util.ConcurrentReferenceHashMap;
// 创建高并发场景下的引用Map (类似WeakHashMap但线程安全)
Map<String, Object> cache = new ConcurrentReferenceHashMap<>();
cache.put("key1", new LargeObject());
反射和类处理工具
7.ReflectionUtils
import org.springframework.util.ReflectionUtils;
// 获取类的字段
Field field = ReflectionUtils.findField(Person.class, "name");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, person, "John");
// 调用方法
Method method = ReflectionUtils.findMethod(Person.class, "setAge", int.class);
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, person, 30);
// 字段回调
ReflectionUtils.doWithFields(Person.class, field -> {
System.out.println(field.getName());
});
8.ClassUtils
import org.springframework.util.ClassUtils;
// 获取类名
String shortName = ClassUtils.getShortName("org.example.MyClass"); // "MyClass"
// 检查类是否存在
boolean exists = ClassUtils.isPresent("java.util.List", null); // true
// 获取所有接口
Class<?>[] interfaces = ClassUtils.getAllInterfaces(ArrayList.class);
// 获取用户定义的类加载器
ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
9.BeanUtils
import org.springframework.beans.BeanUtils;
// 复制属性
Person source = new Person("John", 30);
Person target = new Person();
BeanUtils.copyProperties(source, target);
// 实例化类
Person newPerson = BeanUtils.instantiateClass(Person.class);
// 查找方法
Method method = BeanUtils.findMethod(Person.class, "setName", String.class);
I/O和资源工具
10.FileCopyUtils
import org.springframework.util.FileCopyUtils;
// 复制文件内容
byte[] bytes = FileCopyUtils.copyToByteArray(new File("input.txt"));
FileCopyUtils.copy(bytes, new File("output.txt"));
// 读取文本
String content = FileCopyUtils.copyToString(
new InputStreamReader(new FileInputStream("input.txt"), "UTF-8"));
// 流复制
FileCopyUtils.copy(inputStream, outputStream);
Web相关工具类
11. WebUtils
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
// 获取Cookie
Cookie cookie = WebUtils.getCookie(request, "sessionId");
// 获取请求路径
String path = WebUtils.getLookupPathForRequest(request);
// 从请求中获取参数
int pageSize = WebUtils.getIntParameter(request, "pageSize", 10);
12.UriUtils
import org.springframework.web.util.UriUtils;
// 编解码URI组件
String encoded = UriUtils.encodePathSegment("path with spaces", "UTF-8");
String decoded = UriUtils.decode(encoded, "UTF-8");
验证和断言工具
13.Assert
import org.springframework.util.Assert;
// 常用断言
Assert.notNull(object, "Object must not be null");
Assert.hasText(name, "Name must not be empty");
Assert.isTrue(amount > 0, "Amount must be positive");
Assert.notEmpty(items, "Items must not be empty");
Assert.state(isInitialized, "Service is not initialized");
14.ObjectUtils
import org.springframework.util.ObjectUtils;
// 对象工具
boolean isEmpty = ObjectUtils.isEmpty(null); // true
boolean isEmpty2 = ObjectUtils.isEmpty(new String[0]); // true
String nullSafe = ObjectUtils.nullSafeToString(null); // "null"
boolean equals = ObjectUtils.nullSafeEquals(obj1, obj2);
// 默认值
String value = ObjectUtils.getOrDefault(null, "default");
15. NumberUtils
import org.springframework.util.NumberUtils;
// 数字转换
Integer parsed = NumberUtils.parseNumber("42", Integer.class);
Double converted = NumberUtils.convertNumberToTargetClass(42, Double.class);
日期和时间工具
16.DateTimeUtils
import org.springframework.format.datetime.DateTimeFormatUtils;
import java.util.Date;
// 格式化日期
String formatted = DateTimeFormatUtils.getDateTimeInstance().format(new Date());
17.StopWatch
import org.springframework.util.StopWatch;
// 计时工具
StopWatch watch = new StopWatch("TaskName");
watch.start("phase1");
// 执行任务1
Thread.sleep(100);
watch.stop();
watch.start("phase2");
// 执行任务2
Thread.sleep(200);
watch.stop();
// 输出报告
System.out.println(watch.prettyPrint());
System.out.println("Total time: " + watch.getTotalTimeMillis() + "ms");
安全相关工具
18.Base64Utils
import org.springframework.util.Base64Utils;
// Base64编解码
byte[] data = "Hello World".getBytes();
String encoded = Base64Utils.encodeToString(data);
byte[] decoded = Base64Utils.decodeFromString(encoded);
JSON和数据转换工具
19.JsonUtils
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
// JSON解析
JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, Object> parsed = parser.parseMap("{"name":"John", "age":30}");
List<Object> parsedList = parser.parseList("[1, 2, 3]");
总结
这些工具类涵盖了Java开发中的大部分常见场景,从基础的字符串处理到高级的反射操作,从文件IO到安全加密,从Web开发到性能监控。熟练掌握这些工具类可以显著提高开发效率,减少样板代码。
相关推荐
- Trump Pushes for 15%-20% Minimum Tariffs on EU, Sticks to Auto Duties: Report
-
TMTPOST--U.S.PresidentDonaldTrumpistakingatougherstanceduringtradenegotiationswiththe...
- Note-15.使用A4988控制步进电机(dvp15mc11t控制步进电机)
-
如果需要控制一堆步进电机,那么只使用一个Arduino来控制,就会占用大量的处理时间,而无法处理其他事情,除非使用一个独立的专用步进电机驱动器:A4988。A4988只需两个引脚就可以控制双极步进电机...
- Negotiated settlement, not sanctions, the right way to end the Ukraine crisis
-
Negotiatedsettlement,notsanctions,therightwaytoendtheUkrainecrisis:ChinaDailyeditorial...
- U.S. Services May be Added to EU's Retaliatory Target List as More Members Seek Powerful Trade Tool If Talks Fail
-
TMTPOST--AmericanservicescouldbeaddedtotheEuropeanUnion’sretaliatorytargetlist,highlig...
- S7-1200伺服指令运动指令(s71200伺服位置控制实例)
-
1.MC_Halt指令名称:停止轴运行指令功能:停止所有运动并以组态的减速度停止轴。使用技巧:常用MC_Halt指令来停止通过MC_MoveVelocity指令触发的轴的运行。『注意』部分输入/输出管...
- Deepseek太强了!等了10年的Excel模糊下拉,竟然5分钟就搞定了
-
今天跟大家分享下我们如何通过Deepseek来编写VBA代码,制作模糊搜索的下拉菜单,这个等来十来年的功能,用Deepseek竟然几分钟就搞定了,不得不感叹AI工具的强大,我们以后能干的过AI吗,这真...
- 7.Unity物理关节(unity物理骨骼)
-
7.物理关节Unity的物理关节组件将刚体连接到另一个刚体或空间中的固定点。施加使刚体移动的力,关节限制可以限制移动。关节赋予刚体一定的自由度,从而使这些刚体具有不同的运动。Unity提供的物理关...
- 西门子111报文对应FB284引脚(西门子111报文详解)
-
西门子FB284是基于111报文的功能块,使用FB284比较方便,直接调用就可以控制V90伺服的定位控制。下面是整理的FB284对应的111报文。便于理解FB284功能块,更方面应用在实际项目中。11...
- 数据质量动态探查及相关前端实现(数据质量改进实践指南)
-
需求背景数据探查上线之前,数据验证都是通过写SQL方式进行查询的,从编写SQL,到解析运行出结果,不仅时间长,还会反复消耗计算资源,探查上线后,只需要一次探查,就可以得到整张表的探查报告,但后续...
- 阿里面试官:你连个排序算法都讲不明白?出门右拐吧
-
排序算法一表总览其他注意事项:计数排序中,kkk是整数的范围稳定性是指,序列中相同的数是否有可能交换顺序,例如序列中有两个8,顺序为888和8′8^{'}8′,如果在排序完之后,顺序有...
- 直流电机速度、位置双环控制简明教程
-
速度、位置的双环控制是我们在电机的控制系统中常用的方法,很实用。下面让我们来看一下内部实现的原理。1.速度闭环控制我们一般在速度闭环控制系统里面,使用增量式PI控制。而在我们的微处理器里面,因为控制器...
- 纳米机器人的精准定位与导航(纳米机器人怎么控制位置)
-
纳米机器人的精准定位与导航涉及多学科交叉技术,其“源码”(控制逻辑与算法)需结合硬件特性、环境感知和执行器设计。以下从控制原理、算法逻辑、关键技术实现等方面提供概念性思路(非实际可运行代码),供技术探...
- C语言进阶教程:多级指针的应用(c语言一级指针和二级指针)
-
在C语言中,指针可以指向变量的地址。多级指针(PointerstoPointers或MultilevelPointers)则是指向另一个指针地址的指针。这种概念可以扩展到任意级别(二级指针、...
- 被 Trac 的文件整理能力圈粉了!这 “香” 气挡不住
-
前阵子整理电脑文件夹时,我遇到了个麻烦:上千个文档和照片,要是手动一个个重命名、分类,不仅手得点到发麻,估计还得耗上一上午。于是我就琢磨着,能不能找个办法实现一键批量重命名。我先在网上搜了些批量改名软...
- Enhancer-轻量化的字节码增强组件包
-
一、问题描述当我们的业务发展到一定阶段的时候,系统的复杂度往往会非常高,不再是一个简单的单体应用所能够承载的,随之而来的是系统架构的不断升级与演变。一般对于大型的ToC的互联网企业来说,整个系统都是...
- 一周热门
- 最近发表
-
- Trump Pushes for 15%-20% Minimum Tariffs on EU, Sticks to Auto Duties: Report
- Note-15.使用A4988控制步进电机(dvp15mc11t控制步进电机)
- Negotiated settlement, not sanctions, the right way to end the Ukraine crisis
- U.S. Services May be Added to EU's Retaliatory Target List as More Members Seek Powerful Trade Tool If Talks Fail
- S7-1200伺服指令运动指令(s71200伺服位置控制实例)
- Deepseek太强了!等了10年的Excel模糊下拉,竟然5分钟就搞定了
- 7.Unity物理关节(unity物理骨骼)
- 西门子111报文对应FB284引脚(西门子111报文详解)
- 数据质量动态探查及相关前端实现(数据质量改进实践指南)
- 阿里面试官:你连个排序算法都讲不明白?出门右拐吧
- 标签列表
-
- HTML 教程 (33)
- HTML 简介 (35)
- HTML 实例/测验 (32)
- HTML 测验 (32)
- JavaScript 和 HTML DOM 参考手册 (32)
- HTML 拓展阅读 (30)
- HTML文本框样式 (31)
- HTML滚动条样式 (34)
- HTML5 浏览器支持 (33)
- HTML5 新元素 (33)
- HTML5 WebSocket (30)
- HTML5 代码规范 (32)
- HTML5 标签 (717)
- HTML5 标签 (已废弃) (75)
- HTML5电子书 (32)
- HTML5开发工具 (34)
- HTML5小游戏源码 (34)
- HTML5模板下载 (30)
- HTTP 状态消息 (33)
- HTTP 方法:GET 对比 POST (33)
- 键盘快捷键 (35)
- 标签 (226)
- HTML button formtarget 属性 (30)
- CSS 水平对齐 (Horizontal Align) (30)
- opacity 属性 (32)