来源:blog.csdn.net/2503_92145588

👉 欢迎加入小哈的星球,你将获得: 专属的项目实战(多个项目) / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论

  • 新项目:《Spring AI 项目实战》正在更新中..., 基于 Spring AI + Spring Boot 3.x + JDK 21;

  • 《从零手撸:仿小红书(微服务架构)》 已完结,基于 Spring Cloud Alibaba + Spring Boot 3.x + JDK 17..., 点击查看项目介绍;演示地址:http://116.62.199.48:7070/

  • 《从零手撸:前后端分离博客项目(全栈开发)》 2期已完结,演示链接:http://116.62.199.48/;

  • 专栏阅读地址:https://www.quanxiaoha.com/column

截止目前,累计输出 100w+ 字,讲解图 4013+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,Spring Cloud Alibaba 等等,戳我加入学习,解锁全部项目,已有4000+小伙伴加入

图片

  • 前言

  • 一、Spring Framework 自带工具类

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

  • 总结表格

  • 结语


前言

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

  • Spring Boot 默认引入的工具类

  • 需要手动添加依赖的第三方工具类

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

一、Spring Framework 自带工具类

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

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

示例:

import org.springframework.util.StringUtils;

publicclass 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;
    }
}

publicclass 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;

publicclass 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;

publicclass 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;

publicclass 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;

publicclass 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;

publicclass 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;

publicclass 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;
    privateint age;
}

publicclass 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;

publicclass 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}
    }

    staticclass User {
        private String name;
        privateint 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;

publicclass 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
    }

    staticclass User {
        private String name;
        privateint 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),避免重复造轮子。

👉 欢迎加入小哈的星球,你将获得: 专属的项目实战(多个项目) / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论

  • 新项目:《Spring AI 项目实战》正在更新中..., 基于 Spring AI + Spring Boot 3.x + JDK 21;

  • 《从零手撸:仿小红书(微服务架构)》 已完结,基于 Spring Cloud Alibaba + Spring Boot 3.x + JDK 17..., 点击查看项目介绍;演示地址:http://116.62.199.48:7070/

  • 《从零手撸:前后端分离博客项目(全栈开发)》 2期已完结,演示链接:http://116.62.199.48/;

  • 专栏阅读地址:https://www.quanxiaoha.com/column

截止目前,累计输出 100w+ 字,讲解图 4013+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,Spring Cloud Alibaba 等等,戳我加入学习,解锁全部项目,已有4000+小伙伴加入

图片

图片

图片

1. 我的私密学习小圈子,从0到1手撸企业实战项目~
2. 面试官:如果不允许线程池丢弃任务,应该选择哪个拒绝策略?
3. 5种主流的API架构风格
4. xxl-job 中那些惊艳的架构设计
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
获取方式:点“在看”,关注公众号并回复 Java 领取,更多内容陆续奉上。
PS:因公众号平台更改了推送规则,如果不想错过内容,记得读完点一下“在看”,加个“星标”,这样每次新文章推送才会第一时间出现在你的订阅列表里。
点“在看”支持小哈呀,谢谢啦
Logo

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

更多推荐