SpringBoot 在 spring-core 里准备了这些工具类,不用自己造轮子。下面这 20 个工具类,是我平时写代码最常用的。
1. StringUtils 字符串处理
场景:用户提交表单,判断昵称是否为空。
if (StringUtils.hasText(nickname)) {
// 有内容才进来
}
hasText() 自动判 null、去空格、判空字符串,一行搞定。
2. CollectionUtils 集合操作
场景:查询用户标签,可能返回 null,遍历前先判断。
if (CollectionUtils.isEmpty(tags)) {
return;
}
// 继续处理
3. ObjectUtils 对象工具
场景:日志打印对象,避免 null 指针。
log.info("用户信息:{}", ObjectUtils.nullSafeToString(user));
nullSafeToString() 自动处理 null。
4. Assert 断言工具
场景:接口入参校验,ID不能为空。
Assert.notNull(userId, "用户ID不能为空");
参数不对,直接抛 IllegalArgumentException。
5. FileCopyUtils 文件拷贝
场景:上传文件后,保存到本地。
FileCopyUtils.copy(inputStream, new FileOutputStream(targetFile));
支持流、字节数组、文件之间互拷,简单粗暴。
6. StreamUtils 流操作增强
场景:读取配置文件流,转成字符串。
String content = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
比 IOUtils.toString() 更轻量,而且是 Spring 自家的,不怕依赖冲突。
7. ResourceUtils 资源路径解析
场景:读取 classpath 下的证书文件。
File file = ResourceUtils.getFile("classpath:cert/apiclient_cert.p12");
自动识别 classpath:、file: 等协议,不用再手动拼路径了。
8. ReflectionUtils 反射工具
场景:动态调用某个私有方法(比如测试用)。
Method method = ReflectionUtils.findMethod(UserService.class, "sendWelcomeEmail");
ReflectionUtils.invokeMethod(method, userService, userId);
找方法、调方法、设字段,都不用再写 setAccessible(true) 了。
9. AopProxyUtils AOP 工具
场景:想获取代理对象的真实类型。
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(proxy);
调试时特别有用,不然 getClass() 拿到的是 EnhancerBySpringCGLIB。
10. DigestUtils 加密工具
场景:用户密码 MD5 加密(仅做演示,生产建议用 BCrypt)。
String md5 = DigestUtils.md5DigestAsHex("123456".getBytes());
MD5、SHA-256 都支持,不用再引入 Commons Codec 了。
11. Base64Utils Base64 编解码
场景:把图片转成Base64嵌入HTML。
String base64 = Base64Utils.encodeToString(imageBytes);
注意:它在 org.springframework.util 包下,不是JDK的。
12. StopWatch 代码耗时统计
场景:想知道某个方法执行了多久。
StopWatch watch = new StopWatch();
watch.start("查询订单");
orderService.listOrders();
watch.stop();
watch.start("发送通知");
notifyService.send();
watch.stop();
System.out.println(watch.prettyPrint());
输出清晰,适合日志或调试。
13. AntPathMatcher 路径匹配
场景:判断URL是否匹配某个模式,比如 /api/user/**。
PathMatcher matcher = new AntPathMatcher();
boolean match = matcher.match("/api/user/**", requestPath);
Spring MVC 路由底层就是它,拿来即用。
14. MimeTypeUtils MIME类型解析
场景:根据文件后缀判断类型。
MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
配合响应头设置 Content-Type 很方便。
15. ClassUtils 类操作工具
场景:判断某个类是否存在(比如动态加载功能)。
boolean hasRedis = ClassUtils.isPresent("redis.clients.jedis.Jedis", null);
避免 Class.forName() 报 ClassNotFoundException。
16. SystemPropertyUtils 系统属性占位符解析
场景:配置里写了 ${user.home}/logs,想解析成真实路径。
String path = SystemPropertyUtils.resolvePlaceholders("${user.home}/logs");
自动替换为系统属性值。
17. NumberUtils 数字工具
场景:字符串转数字,避免异常。
int num = NumberUtils.parseNumber("123", Integer.class);
比 Integer.parseInt 更安全。
18. ConcurrentReferenceHashMap 并发弱引用Map
场景:缓存场景,自动回收无用对象。
ConcurrentReferenceHashMap<String, Object> map = new ConcurrentReferenceHashMap<>();
比 ConcurrentHashMap 更省内存。
19. LinkedMultiValueMap 多值Map
场景:一个 key 对应多个 value,比如表单参数。
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("hobby", "篮球");
map.add("hobby", "足球");
取出来是 List。
20. UriComponentsBuilder URL 构建工具
场景:拼接URL参数,防止手写出错。
String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/api")
.queryParam("id", 1)
.queryParam("name", "张三")
.toUriString();
自动编码参数,安全可靠。
以上工具类都在 Spring Framework 的
spring-core、spring-web等包下,建议多用,能极大提升开发效率和代码健壮性。
转自:https://www.codefather.cn/post/1962356505304559618#heading-19
评论区