惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
月光博客
月光博客
Jina AI
Jina AI
宝玉的分享
宝玉的分享
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
V
V2EX
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
B
Blog
博客园 - 叶小钗
小众软件
小众软件
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
A
About on SuperTechFans
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog

博客园 - KLAPT

Spring Web MVC 中,过滤器(Filter) 和 拦截器(Interceptor) SpringBoot API 接口防刷 ROW_NUMBER() 一台服务器最大能支持多少条 TCP 连接 Gateway 网关 CodeX =>Skills Redis 内存满了怎么处理 SpringBoot 默认配置修改 JWT 续签 Access Token + Refresh Token 双 Token claudeCode 命令 MyBatis 的 Mapper 接口 AI | CC GUI 集成 IDEA 完整教程 在IDEA中使用Claude Code IDEA中使用CodeX MyBatisPlus解决大数据量查询慢问题 idea 中的 claude code Token Dubbo 和 Spring Cloud Gateway的区别 Transactional 注解中propagation 掌握 Spring 框架这 10 个扩展点 SpringBoot 快速实现 api 加密 Spring Boot/Cloud 中 bootstrap.yml 与 application.yml SpringBoot 实现 DOCX 转 PDF 微服务Token鉴权设计的几种方案 进程、线程、协程 RSA 加密 Java二维码 ntp服务端和客户端 Chronyd与NTP chronyd 作为服务器时钟
Spring Framework 自带工具类
KLAPT · 2026-09-17 · via 博客园 - KLAPT

1.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 提供了反射相关的便捷方法,使开发者能够更容易地访问私有字段、调用私有方法等。

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

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 提供了一些与类加载相关的便捷方法,如判断某个类是否是另一个类的子类,或者检查类是否存在。

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 提供了资源文件的定位和加载支持,对于读取配置文件、模板文件等非常有用。

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());
        }
    }
}

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

1. Apache Commons Lang3 (commons-lang3)

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)

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)


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)

// 自动生成 getter/setter/toString 等
@Data
@AllArgsConstructor 
@NoArgsConstructor=======》

  • 如果类中有 final 字段或 @NonNull 字段未初始化,编译会报错,因为无参构造无法给它们赋值。

  • 可以通过 @NoArgsConstructor(force = true) 强制生成,此时 final 字段会被赋默认值(0 / false / null)。


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 序列化与反序列化工具。

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

    static  class 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)

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