Spring Framework的常用工具类

如果你的项目是基于 Spring Boot 的,Spring Boot 会自动引入 Spring 的核心依赖。

Spring Boot 的 spring-boot-starter 自动包含了 Spring Core 和其他必要模块,因此你无需单独引入 spring-corespring-beans

1. StringUtils

StringUtils 提供了对字符串处理的常用方法,可以减少对原生 Java 的 String 类复杂操作的依赖。

常用方法:

  • isEmpty(String str)

    判断字符串是否为空或长度为 0。

  • hasText(String str)

    判断字符串是否包含非空格字符。

  • hasLength(String str)

    判断字符串是否非空(不为空指针,且长度大于等于 0)。

  • trimWhitespace(String str)

    去除字符串中的所有空白字符(包括首尾和中间的)。

  • commaDelimitedListToStringArray(String str)

    将以逗号分隔的字符串转为数组。

  • arrayToCommaDelimitedString(Object[] arr)

    将数组转为以逗号分隔的字符串。

使用示例:

java 复制代码
String text = "  Spring ";
System.out.println(StringUtils.hasText(text)); // true
System.out.println(StringUtils.trimWhitespace(text)); // "Spring"
System.out.println(StringUtils.isEmpty(null)); // true

2. CollectionUtils

CollectionUtils 提供了对集合(Collection)和映射(Map)的操作工具。

常用方法:

  • isEmpty(Collection<?> collection)

    判断集合是否为空或为 null

  • isEmpty(Map<?, ?> map)

    判断 Map 是否为空或为 null

  • containsAny(Collection<?> source, Collection<?> candidates)

    检查 source 中是否包含 candidates 的任一元素。

  • mergeArrayIntoCollection(Object[] array, Collection<E> collection)

    将数组的内容合并到集合中。

  • findFirstMatch(Collection<?> source, Collection<?> candidates)

    查找 source 中第一个与 candidates 匹配的元素。

使用示例:

java 复制代码
List<String> list = Arrays.asList("A", "B", "C");
System.out.println(CollectionUtils.isEmpty(list)); // false
System.out.println(CollectionUtils.containsAny(list, Arrays.asList("B", "D"))); // true

3. ObjectUtils

ObjectUtils 提供了对 Object 的一些操作工具。

常用方法:

  • isEmpty(Object obj)

    判断对象是否为空(包括空数组、空集合等)。

  • nullSafeEquals(Object o1, Object o2)

    安全地比较两个对象是否相等,避免 NullPointerException

  • identityToString(Object obj)

    返回对象的唯一标识(类名+哈希值)。

  • hashCode(Object obj)

    返回对象的哈希码。

  • isArray(Object obj)

    判断对象是否为数组。

使用示例:

java 复制代码
System.out.println(ObjectUtils.isEmpty(null)); // true
System.out.println(ObjectUtils.isEmpty(new int[]{})); // true
System.out.println(ObjectUtils.nullSafeEquals("Spring", "Spring")); // true

4. Assert

Assert 是一个断言工具类,可以在代码中使用它来校验参数或状态,避免空指针异常或逻辑错误。

常用方法:

  • notNull(Object object, String message)

    检查对象是否为空,如果为空抛出 IllegalArgumentException

  • hasText(String text, String message)

    检查字符串是否包含有效文本。

  • notEmpty(Collection<?> collection, String message)

    检查集合是否为空。

  • isTrue(boolean expression, String message)

    检查表达式是否为真。

使用示例:

java 复制代码
public void process(String input) {
    Assert.notNull(input, "Input must not be null");
    Assert.hasText(input, "Input must contain text");
}

5. ResourceResourceLoader

用于方便地加载资源文件。

常用方法:

  • getInputStream()

    获取资源文件的输入流。

  • 支持加载多种资源形式:

    • ClassPathResource:加载类路径下的资源。
    • FileSystemResource:加载文件系统中的资源。
    • UrlResource:通过 URL 加载资源。

使用示例:

java 复制代码
Resource resource = new ClassPathResource("application.properties");
try (InputStream input = resource.getInputStream()) {
    Properties props = new Properties();
    props.load(input);
    System.out.println(props.getProperty("spring.application.name"));
}

6.FileCopyUtils

FileCopyUtils 用于处理文件和流的复制操作,简化了文件 IO。

常用方法:

  • copy(InputStream in, OutputStream out)

    将输入流复制到输出流。

  • copy(byte[] in, File out)

    将字节数组复制到文件。

  • copyToByteArray(InputStream in)

    将输入流复制为字节数组。

使用示例:

java 复制代码
File source = new File("source.txt");
File target = new File("target.txt");
FileCopyUtils.copy(new FileInputStream(source), new FileOutputStream(target));

7. DigestUtils

DigestUtils 用于生成文件或字符串的 MD5 或 SHA1 摘要。

常用方法:

  • md5Digest(byte[] bytes)

    返回 MD5 的字节数组。

  • md5DigestAsHex(byte[] bytes)

    返回 MD5 的十六进制字符串。

使用示例:

java 复制代码
String password = "mySecret";
String hashed = DigestUtils.md5DigestAsHex(password.getBytes());
System.out.println(hashed);

8.BeanUtils

BeanUtils 用于处理 JavaBean 的属性拷贝和实例化。

常用方法:

  • copyProperties(Object source, Object target)

    将源对象的属性值复制到目标对象中。

  • instantiateClass(Class<T> clazz)

    创建一个类的实例(调用无参构造函数)。

使用示例:

java 复制代码
public class User {
    private String name;
    private int age;
    // Getters and Setters
}

User source = new User();
source.setName("John");
source.setAge(30);

User target = new User();
BeanUtils.copyProperties(source, target);
System.out.println(target.getName()); // John

总结

用途 工具类 作用 示例代码
字符串操作 StringUtils 判断是否为空、去空格、分割/拼接字符串 StringUtils.hasText("Spring");
集合操作 CollectionUtils 判断集合是否为空、检查是否包含元素 CollectionUtils.isEmpty(list);
对象操作 ObjectUtils 判断对象是否为空、安全比较两个对象 ObjectUtils.isEmpty(obj);
参数校验 Assert 校验参数是否为空或符合要求,避免非法输入 Assert.notNull(obj, "Must not be null");
资源加载 Resource 加载配置文件、模板文件或静态资源 new ClassPathResource("file.txt");
数据摘要 DigestUtils 生成 MD5 等摘要,用于密码加密或文件校验 DigestUtils.md5DigestAsHex("data".getBytes());
属性拷贝 BeanUtils 拷贝对象属性,简化 DTO 转换 BeanUtils.copyProperties(src, target);
相关推荐
MacroZheng5 分钟前
换掉ES!SpringBoot + Meilisearch实现商品搜索,太方便了!
java·spring boot·后端
{⌐■_■}11 分钟前
【计网】认识跨域,及其在go中通过注册CORS中间件解决跨域方案,go-zero、gin
java·linux·开发语言·c++·中间件·golang·gin
猿java25 分钟前
什么是Nginx?它有哪些应用场景?
java·nginx·面试
DBWYX29 分钟前
redis
java·redis·mybatis
mask哥30 分钟前
实用的java技术架构组件汇总
java·spring·微服务·springboot·vo校验·常用java组件
不穿铠甲的穿山甲42 分钟前
gradle-tasks.register(‘classesJar‘, Jar)解析
android·java·gradle·groovy
学了就忘1 小时前
Axios 传参与 Spring Boot 接收参数完全指南
java·spring boot·后端·vue
漂流瓶6666661 小时前
如何在idea中写spark程序
java·spark·intellij-idea
冼紫菜1 小时前
[特殊字符] SpringCloud项目中使用OpenFeign进行微服务远程调用详解(含连接池与日志配置)
java·后端·spring cloud
oioihoii1 小时前
C++23文本编码革新:迈向更现代的字符处理
java·数据库·c++23