在 SpringBoot 开发中,我们常常需要处理字符串、集合、文件、日期等常见任务。幸运的是,Spring 框架早已为我们准备了大量经过充分测试、稳定高效的工具类,它们隐藏在 spring-corespring-web 等模块中,功能强大且无需额外引入依赖。

本文将为你盘点 SpringBoot 内置的 20 个高效工具类,并提供实用代码示例,助你提升开发效率,写出更简洁、更健壮的代码。


1. StringUtils - 字符串处理大师
  • 包路径org.springframework.util.StringUtils
  • 用途:判空、分割、拼接、格式化等。
  • 示例
    // 判断字符串是否有内容(非空且非纯空白)
    if (StringUtils.hasText(username)) {
        System.out.println("用户名有效");
    }
    
    // 安全分割字符串
    String[] parts = StringUtils.commaDelimitedListToStringArray("a,b,c");
    
2. CollectionUtils - 集合操作利器
  • 包路径org.springframework.util.CollectionUtils
  • 用途:判断集合是否为空、合并、转换。
  • 示例
    List<String> list = new ArrayList<>();
    if (CollectionUtils.isEmpty(list)) {
        System.out.println("列表为空");
    }
    
3. ObjectUtils - 对象通用工具
  • 包路径org.springframework.util.ObjectUtils
  • 用途:安全比较、获取哈希值。
  • 示例
    // 安全比较两个对象,避免 null 异常
    boolean isEqual = ObjectUtils.nullSafeEquals(obj1, obj2);
    
4. Assert - 断言工具(参数校验)
  • 包路径org.springframework.util.Assert
  • 用途:替代 if 判断,抛出 IllegalArgumentException
  • 示例
    // 如果 id 为 null 或 <=0,抛出异常
    Assert.notNull(id, "ID 不能为空");
    Assert.isTrue(id > 0, "ID 必须大于 0");
    
5. FileCopyUtils - 文件拷贝助手
  • 包路径org.springframework.util.FileCopyUtils
  • 用途:流与流之间高效拷贝。
  • 示例
    // 将输入流转为字节数组
    byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
    
    // 拷贝文件流
    FileCopyUtils.copy(inputStream, outputStream);
    
6. StreamUtils - 流操作增强
  • 包路径org.springframework.util.StreamUtils
  • 用途:增强流操作,支持 DataBuffer
  • 示例
    // 读取流并转为字符串
    String content = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
    
7. ResourceUtils - 资源定位专家
  • 包路径org.springframework.util.ResourceUtils
  • 用途:判断资源路径类型,获取文件。
  • 示例
    // 判断是否为 classpath 资源
    if (ResourceUtils.isUrl("classpath:application.yml")) {
        System.out.println("是资源路径");
    }
    
8. ReflectionUtils - 反射操作封装
  • 包路径org.springframework.util.ReflectionUtils
  • 用途:调用私有方法、设置字段值。
  • 示例
    // 调用私有方法
    Method method = ReflectionUtils.findMethod(User.class, "privateMethod");
    ReflectionUtils.invokeMethod(method, userInstance);
    
9. AopProxyUtils - AOP 代理工具
  • 包路径org.springframework.aop.support.AopProxyUtils
  • 用途:获取代理对象的真实目标类。
  • 示例
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(proxyObject);
    
10. BeanUtils - JavaBean 操作神器
  • 包路径org.springframework.beans.BeanUtils
  • 用途:对象属性拷贝。
  • 示例
    User user = new User("张三", 25);
    UserDTO dto = new UserDTO();
    // 将 user 的属性复制到 dto
    BeanUtils.copyProperties(user, dto);
    
11. ConversionService - 类型转换服务
  • 包路径org.springframework.core.convert.ConversionService
  • 用途:类型安全转换。
  • 示例
    @Autowired
    private ConversionService conversionService;
    
    Integer num = conversionService.convert("123", Integer.class);
    
12. MimeTypeUtils - MIME 类型解析
  • 包路径org.springframework.util.MimeTypeUtils
  • 用途:创建和解析 MIME 类型。
  • 示例
    MimeType jsonType = MimeTypeUtils.APPLICATION_JSON;
    System.out.println(jsonType.toString()); // application/json
    
13. Base64Utils - Base64 编解码
  • 包路径org.springframework.util.Base64Utils
  • 用途:Base64 编码/解码。
  • 示例
    String encoded = Base64Utils.encodeToString("Hello".getBytes());
    byte[] decoded = Base64Utils.decodeFromString(encoded);
    
14. DigestUtils - 摘要算法工具
  • 包路径org.springframework.util.DigestUtils
  • 用途:生成 MD5、SHA-256。
  • 示例
    String md5 = DigestUtils.md5DigestAsHex("password123".getBytes());
    String sha256 = DigestUtils.sha256DigestAsHex("data".getBytes());
    
15. StopWatch - 代码性能监控
  • 包路径org.springframework.util.StopWatch
  • 用途:监控代码执行时间。
  • 示例
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("任务1");
    Thread.sleep(100);
    stopWatch.stop();
    
    stopWatch.start("任务2");
    Thread.sleep(200);
    stopWatch.stop();
    
    System.out.println(stopWatch.prettyPrint()); // 输出各任务耗时
    
16. WebUtils - Web 请求辅助
  • 包路径org.springframework.web.util.WebUtils
  • 用途:获取请求参数、Cookie。
  • 示例
    // 获取请求中的参数
    String value = WebUtils.findParameterValue(request, "name");
    
17. UriComponentsBuilder - URL 构建器
  • 包路径org.springframework.web.util.UriComponentsBuilder
  • 用途:构建复杂 URL。
  • 示例
    String url = UriComponentsBuilder.fromHttpUrl("https://api.example.com/user")
        .queryParam("id", 1)
        .queryParam("name", "张三")
        .encode()
        .toUriString();
    // 结果: https://api.example.com/user?id=1&name=%E5%BC%A0%E4%B8%89
    
18. HtmlUtils - HTML 转义工具
  • 包路径org.springframework.web.util.HtmlUtils
  • 用途:防止 XSS 攻击。
  • 示例
    String safe = HtmlUtils.htmlEscape("<script>alert(1)</script>");
    // 结果: &lt;script&gt;alert(1)&lt;/script&gt;
    
19. AssertRequestContextHolder - 异步上下文工具
  • 说明:虽然没有独立工具类名,但 RequestContextHolder 可在异步线程中获取 HttpServletRequest
  • 示例
    // 在异步线程中获取请求
    RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
    
20. ClassUtils - 类操作工具
  • 包路径org.springframework.util.ClassUtils
  • 用途:加载类、判断类是否存在。
  • 示例
    // 获取类的短名称
    String shortName = ClassUtils.getShortName(User.class);
    
    // 判断类是否存在
    boolean present = ClassUtils.isPresent("com.example.MyClass", null);
    

总结

这 20 个工具类是 SpringBoot 开发的“秘密武器”。它们:

开箱即用:无需额外依赖
稳定高效:经过 Spring 社区长期验证
减少 Bug:避免手动实现带来的空指针等问题

建议

  • 优先使用这些工具类,而不是自己写 if-elsetry-catch
  • 熟记常用类如 AssertBeanUtilsStopWatchStringUtils
  • 查看 Spring 源码,深入理解其实现原理。

🙌 感谢你读到这里!
🔍 技术之路没有捷径,但每一次阅读、思考和实践,都在悄悄拉近你与目标的距离。
💡 如果本文对你有帮助,不妨 👍 点赞、📌 收藏、📤 分享 给更多需要的朋友!
💬 欢迎在评论区留下你的想法、疑问或建议,我会一一回复,我们一起交流、共同成长 🌿
🔔 关注我,不错过下一篇干货!我们下期再见!✨

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐