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

Spring Boot 中常用的工具类库及其使用示例(完整版)

前言

在开发 Spring Boot 项目时,我们经常会用到各种实用工具类来简化代码、提升效率。本文将这些工具类分为两类:

  • Spring Boot 默认引入的工具类
  • 需要手动添加依赖的第三方工具类

每类工具都会列出 至少三个常用方法的使用示例,帮助你快速掌握其用法。


一、Spring Framework 自带工具类

Spring Framework 提供了一系列实用工具类,这些工具类在日常开发中非常有用,可以减少重复代码并提高效率。以下是一些常用的工具类及其使用示例。

1. org.springframework.util.StringUtils

StringUtils 是一个处理字符串操作的工具类,提供了许多静态方法来简化常见的字符串操作任务。

示例:
import org.springframework.util.StringUtils;public class StringUtilsExample {public static void main(String[] args) {// 判断字符串是否有内容(非空且不全是空白)boolean hasText = StringUtils.hasText("Hello, Spring!");System.out.println("Does the string have text? " + hasText); // true// 判断字符串是否为空(null 或长度为0)boolean isEmpty = StringUtils.isEmpty("");System.out.println("Is the string empty? " + isEmpty); // true// 将数组元素连接成字符串String[] words = {"Hello", "world"};String joinedString = StringUtils.arrayToDelimitedString(words, " ");System.out.println("Joined string: " + joinedString); // Hello world}
}

2. org.springframework.util.ReflectionUtils

ReflectionUtils 提供了反射相关的便捷方法,使开发者能够更容易地访问私有字段、调用私有方法等。

示例:
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;class Person {private String name = "John";public String getName() {return name;}
}public class ReflectionUtilsExample {public static void main(String[] args) throws IllegalAccessException {Person person = new Person();// 获取并设置私有字段值Field field = ReflectionUtils.findField(Person.class, "name");ReflectionUtils.makeAccessible(field);field.set(person, "Jane");System.out.println("Name after reflection modification: " + person.getName()); // Jane// 使用反射获取字段值Object value = ReflectionUtils.getField(field, person);System.out.println("Value retrieved by reflection: " + value); // Jane// 查找所有方法ReflectionUtils.doWithMethods(Person.class, method -> System.out.println("Method found: " + method.getName()));}
}

3. org.springframework.util.Assert

Assert 类提供了断言功能,用于验证程序状态或参数的有效性。如果条件不满足,则会抛出相应的异常。

示例:
import org.springframework.util.Assert;public class AssertExample {public static void main(String[] args) {try {// 校验对象是否为 nullAssert.notNull(null, "Object must not be null");} catch (IllegalArgumentException e) {System.out.println(e.getMessage()); // Object must not be null}try {// 校验字符串是否为空Assert.hasText("", "Text must not be empty");} catch (IllegalArgumentException e) {System.out.println(e.getMessage()); // Text must not be empty}try {// 校验表达式是否为 trueAssert.isTrue(5 < 4, "Expression is false");} catch (IllegalArgumentException e) {System.out.println(e.getMessage()); // Expression is false}}
}

4. org.springframework.util.ClassUtils

ClassUtils 提供了一些与类加载相关的便捷方法,如判断某个类是否是另一个类的子类,或者检查类是否存在。

示例:
import org.springframework.util.ClassUtils;public class ClassUtilsExample {public static void main(String[] args) {// 判断是否实现了接口boolean isAssignable = ClassUtils.isAssignable(java.util.List.class, java.util.ArrayList.class);System.out.println("Is ArrayList assignable from List? " + isAssignable); // true// 获取简短类名String shortClassName = ClassUtils.getShortName("java.util.ArrayList");System.out.println("Short class name: " + shortClassName); // ArrayList// 判断类是否存在boolean exists = ClassUtils.isPresent("java.util.ArrayList", ClassUtilsExample.class.getClassLoader());System.out.println("ArrayList class present? " + exists); // true}
}

5. org.springframework.util.ResourceUtils

ResourceUtils 提供了资源文件的定位和加载支持,对于读取配置文件、模板文件等非常有用。

示例:
import org.springframework.util.ResourceUtils;import java.io.File;
import java.io.FileNotFoundException;public class ResourceUtilsExample {public static void main(String[] args) {try {// 加载classpath下的资源文件File file = ResourceUtils.getFile("classpath:application.properties");System.out.println("File path: " + file.getAbsolutePath());// 加载文件系统中的文件File systemFile = ResourceUtils.getFile("file:/path/to/your/file.txt");System.out.println("System file path: " + systemFile.getAbsolutePath());} catch (FileNotFoundException e) {System.err.println("File not found: " + e.getMessage());}}
}

二、需要手动添加依赖的工具类库

以下工具类需要手动添加 Maven 或 Gradle 依赖后才能使用。


1. Apache Commons Lang3 (commons-lang3)

提供丰富的字符串、对象、数组操作工具。

示例:
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ArrayUtils;public class CommonsLang3Example {public static void main(String[] args) {// 判断字符串是否为空System.out.println(StringUtils.isEmpty(null)); // trueSystem.out.println(StringUtils.isEmpty("")); // trueSystem.out.println(StringUtils.isEmpty("abc")); // false// 随机生成6位字符串System.out.println(StringUtils.randomAlphanumeric(6)); // 如:7xK9mL// 合并两个数组int[] arr1 = {1, 2, 3};int[] arr2 = {4, 5};int[] merged = ArrayUtils.addAll(arr1, arr2);for (int i : merged) {System.out.print(i + " "); // 1 2 3 4 5}}
}

2. Google Guava (guava)

提供函数式编程支持、集合增强、Optional、断言等功能。

示例:
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.base.Optional;public class GuavaExample {public static void main(String[] args) {// 参数检查try {Preconditions.checkNotNull(null, "Value can't be null");} catch (Exception e) {System.out.println(e.getMessage()); // Value can't be null}// 创建不可变列表List<String> list = Lists.newArrayList("Java", "Python", "Go");System.out.println(list); // [Java, Python, Go]// 使用 Optional 处理可能为 null 的值Optional<String> optional = Optional.fromNullable(null);System.out.println(optional.or("default")); // default}
}

3. Hutool (hutool-all)

国产 Java 工具类库,功能丰富,几乎涵盖所有日常需求。

示例:
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;public class HutoolExample {public static void main(String[] args) {// 判断字符串是否为空System.out.println(StrUtil.isEmpty("")); // trueSystem.out.println(StrUtil.isEmpty("hello")); // false// 生成随机数字System.out.println(RandomUtil.randomNumbers(6)); // 如:832917// 发送 HTTP GET 请求String result = HttpUtil.get("https://jsonplaceholder.typicode.com/posts/1");System.out.println(result); // {"userId":1,"id":1,"title":"..."}}
}

4. Lombok (lombok)

编译期自动生成代码,减少样板代码编写。

示例:
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;// 自动生成 getter/setter/toString 等
@Data
@AllArgsConstructor
@NoArgsConstructor
class User {private String name;private int age;
}public class LombokExample {public static void main(String[] args) {User user = new User("Tom", 25);System.out.println(user.toString()); // User(name=Tom, age=25)}
}

5. Jackson (jackson-databind)

JSON 序列化与反序列化工具。

示例:
import com.fasterxml.jackson.databind.ObjectMapper;public class JacksonExample {public static void main(String[] args) throws Exception {ObjectMapper mapper = new ObjectMapper();// 对象转 JSON 字符串User user = new User("Alice", 30);String json = mapper.writeValueAsString(user);System.out.println(json); // {"name":"Alice","age":30}// JSON 字符串转对象String jsonInput = "{\"name\":\"Bob\",\"age\":28}";User parsedUser = mapper.readValue(jsonInput, User.class);System.out.println(parsedUser.getName()); // Bob// 忽略空字段输出user.setName(null);System.out.println(mapper.writeValueAsString(user)); // {"age":30}}static class User {private String name;private int age;// 构造器、getter/setter 省略public User(String name, int age) {this.name = name;this.age = age;}public String getName() { return name; }public void setName(String name) { this.name = name; }public int getAge() { return age; }public void setAge(int age) { this.age = age; }}
}

6. Fastjson (fastjson)

阿里巴巴开源的高性能 JSON 工具(注意安全问题)。

示例:
import com.alibaba.fastjson.JSON;public class FastJsonExample {public static void main(String[] args) {// 对象转 JSON 字符串User user = new User("Charlie", 22);String json = JSON.toJSONString(user);System.out.println(json); // {"age":22,"name":"Charlie"}// JSON 字符串转对象String input = "{\"name\":\"David\",\"age\":29}";User parsed = JSON.parseObject(input, User.class);System.out.println(parsed.getName()); // David// 转 MapString mapJson = "{\"key1\":\"value1\",\"key2\":\"value2\"}";Map<String, String> map = JSON.parseObject(mapJson, Map.class);System.out.println(map.get("key1")); // value1}static class User {private String name;private int age;// 构造器、getter/setter 省略public User(String name, int age) {this.name = name;this.age = age;}public String getName() { return name; }public void setName(String name) { this.name = name; }public int getAge() { return age; }public void setAge(int age) { this.age = age; }}
}

总结表格

工具类库是否默认引入常用功能
Spring Framework 自带工具类字符串处理、反射、断言
Apache Commons Lang3字符串、数组、对象操作
Google Guava集合增强、Optional、断言
Hutool全能型工具库(字符串、HTTP、加密等)
Lombok自动生成 getter/setter、构造器等
Jackson一般已包含JSON 序列化/反序列化
FastjsonJSON 解析(慎用,存在安全隐患)

结语

通过合理使用这些工具类库,我们可以大大提升 Spring Boot 项目的开发效率和代码质量。建议优先使用 Spring 内置工具类或社区活跃度高的第三方库(如 Hutool、Guava),避免重复造轮子。

http://www.lryc.cn/news/580043.html

相关文章:

  • 洛谷P1941 [NOIP 2014 提高组] 飞扬的小鸟
  • 行阶梯形矩阵和行最简形矩阵的区别
  • 【WRFDA教程第十期】混合数据同化(Hybrid Data Assimilation)
  • 【C++复习1】基础篇
  • 负载均衡--常见负载均衡算法
  • 大带宽服务器中冗余技术的功能
  • 【深度解析】Seedance 1.0:重新定义 AI 视频生成的工业级标准
  • 10.双端Diff算法
  • [代码学习] c++ 通过H矩阵快速生成图像对应的mask
  • 嵌入式C语言:指针
  • Jenkins-Email Extension 插件插件
  • ubuntu 18.04配置镜像源
  • ubuntu22桌面版中文输入法 fcitx5
  • 运维打铁:企业云服务解决方案
  • 金融系统中常用的FIX协议
  • 企业电商解决方案哪家好?ZKmall模块商城全渠道支持 + 定制化服务更省心
  • 文本分词 nltk
  • ODS 系统是什么?企业为什么需要搭建 ODS?
  • CentOS配置网络
  • 【Oracle APEX开发小技巧15】多级弹窗关闭子级保留父级
  • 建议大家都去频繁大量地记录自己:让目标在笔尖下生根发芽
  • 【银行测试】手机银行APP专项项目+测试点汇总(一)
  • 【烧脑算法】最小字典序:巧用单调栈,从栈底到最优解
  • Jmeter安装使用-测试Java接口
  • iOS IPA 混淆,如何对企业定制 App 做渠道差异化保护
  • 写一个ununtu C++ 程序,调用ffmpeg , 来判断一个数字电影的音频文件mxf 的 采样率(频率),通道数, 采样位数
  • ARMv8 没开mmu执行memset引起的非对齐访问异常
  • 新商品冷启动:基于语义Embedding与GBRT的消费指标预估技术实践
  • chrome插件合集
  • vue 循环无限滚动表格