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

发布于:2025-07-05 ⋅ 阅读:(11) ⋅ 点赞:(0)

前言

在开发 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 {
            // 校验对象是否为 null
            Assert.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 {
            // 校验表达式是否为 true
            Assert.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)); // true
        System.out.println(StringUtils.isEmpty("")); // true
        System.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("")); // true
        System.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

        // 转 Map
        String 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 序列化/反序列化
Fastjson JSON 解析(慎用,存在安全隐患)

结语

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


网站公告

今日签到

点亮在社区的每一天
去签到