SpringBoot在spring-core里准备了这些工具类,不用自己造轮子。
下面这 20 个工具类,是我平时写代码最常用的。
1.StringUtils字符串处理
场景:用户提交表单,判断昵称是否为空。
// 别再写这种了
if (nickname == null || "".equals(nickname.trim())) {
// ...
}
// 用 Spring 的
if (StringUtils.hasText(nickname)) {
// 有内容才进来
}
hasText()自动判null、去空格、判空字符串,一行搞定。
2.CollectionUtils集合操作
场景:查询用户标签,可能返回 null,遍历前先判断。
// 别这样
if (tags != null && !tags.isEmpty()) {
for (String tag : tags) { ... }
}
// 这样更干净
if (CollectionUtils.isEmpty(tags)) {
return;
}
// 继续处理
3.ObjectUtils对象工具
场景:日志打印对象,避免null指针。
// 以前
log.info("用户信息:" + (user == null ? "null" : user.toString()));
// 现在
log.info("用户信息:{}", ObjectUtils.nullSafeToString(user));
nullSafeToString()自动处理 null。
4.Assert断言工具
场景:接口入参校验,ID不能为空。
// 别写 if + 抛异常
if (userId == null) {
throw new IllegalArgumentException("用户ID不能为空");
}
// 一行搞定
Assert.notNull(userId, "用户ID不能为空");
参数不对,直接抛IllegalArgumentException。
5.FileCopyUtils文件拷贝
场景:上传文件后,保存到本地。
// 以前写 InputStream + OutputStream,一堆 try-catch
// 现在
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.AopProxyUtilsAOP 工具
场景:想获取代理对象的真实类型。
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(proxy);
调试时特别有用,不然getClass()拿到的是EnhancerBySpringCGLIB。
10. DigestUtils 加密工具
场景:用户密码 MD5 加密(仅做演示,生产建议用 BCrypt)。
String md5 = DigestUtils.md5DigestAsHex("123456".getBytes());
MD5、SHA-256 都支持,不用再引入 Commons Codec 了。
11.Base64UtilsBase64 编解码
场景:把图片转成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.MimeTypeUtilsMIME类型解析
场景:根据文件后缀判断类型。
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.SerializationUtils序列化工具
场景:缓存对象,需要深拷贝。
User newUser = SerializationUtils.deserialize(SerializationUtils.serialize(oldUser));
实现深拷贝的一种方式(前提是实现Serializable)。
18.WebUtilsWeb 工具
场景:从 request 中获取 Session,避免空指针。
HttpSession session = WebUtils.getSession(request, false);
还有获取 cookie、判断是否 Ajax 请求等实用方法。
19.NumberUtils数字转换
场景:前端传了个字符串 ID,转成 Long。
Long id = NumberUtils.convertNumberToTargetClass(strId, Long.class);
转换失败会抛异常,比Long.parseLong()更统一。
20. UriUtils URL 编解码
场景:处理带中文的 URL 参数。
String encoded = UriUtils.encodeQueryParam("杭州", StandardCharsets.UTF_8);
比URLEncoder更符合 RFC 标准,特别是处理路径、参数时。
最后
这些工具类都在spring-core里,你项目里基本already have了,根本不用加依赖。
以前我也是每个都手写,后来发现:Spring早就替你想好了。用好它们,代码更短,bug更少。
566

被折叠的 条评论
为什么被折叠?



