百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

SpringBoot中内置常用工具类(springboot工具类读取配置文件)

zhezhongyun 2025-07-24 23:18 36 浏览

前言:

SpringBoot以其强大的自动配置和丰富的生态系统成为Java开发的首选框架。除了核心功能外,SpringBoot及其依赖的Spring框架还包含大量实用工具类,它们可以显著简化日常开发工作。本文将介绍几个用工具类,并通过简洁的代码示例展示它们的基本用法。

字符串处理工具类

1.StringUtils

import org.springframework.util.StringUtils;

// 检查字符串是否为空

boolean isEmpty = StringUtils.isEmpty(null); // true

boolean isEmpty2 = StringUtils.isEmpty(""); // true

// 检查字符串是否有文本内容

boolean hasText = StringUtils.hasText(" "); // false

boolean hasText2 = StringUtils.hasText("hello"); // true

// 分割字符串

String[] parts = StringUtils.tokenizeToStringArray("a,b,c", ",");

// 清除首尾空白

String trimmed = StringUtils.trimWhitespace(" hello "); // "hello"

2.AntPathMatcher

import org.springframework.util.AntPathMatcher;

AntPathMatcher matcher = new AntPathMatcher();

boolean match1 = matcher.match("/users/*", "/users/123"); // true

boolean match2 = matcher.match("/users/**", "/users/123/orders"); // true

boolean match3 = matcher.match("/user?", "/user1"); // true

// 提取路径变量

Map<String, String> vars = matcher.extractUriTemplateVariables("/users/{id}", "/users/42"); // {id=42}

3. PatternMatchUtils

import org.springframework.util.PatternMatchUtils;

boolean matches1 = PatternMatchUtils.simpleMatch("user*", "username"); // true

boolean matches2 = PatternMatchUtils.simpleMatch("user?", "user1"); // true

boolean matches3 = PatternMatchUtils.simpleMatch(new String[]{"user*", "admin*"}, "username"); // true

集合和数组工具类

4. CollectionUtils

import org.springframework.util.CollectionUtils;

// 检查集合是否为空

boolean isEmpty = CollectionUtils.isEmpty(null); // true

boolean isEmpty2 = CollectionUtils.isEmpty(Collections.emptyList()); // true

// 集合操作

List<String> list1 = Arrays.asList("a", "b", "c");

List<String> list2 = Arrays.asList("b", "c", "d");

Collection<String> intersection = CollectionUtils.intersection(list1, list2); // [b, c]

// 合并集合

List<String> target = new ArrayList<>();

CollectionUtils.mergeArrayIntoCollection(new String[]{"a", "b"}, target);

5. MultiValueMap

import org.springframework.util.LinkedMultiValueMap;

import org.springframework.util.MultiValueMap;

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

map.add("colors", "red");

map.add("colors", "blue");

map.add("sizes", "large");

List<String> colors = map.get("colors"); // [red, blue]

6. ConcurrentReferenceHashMap

import org.springframework.util.ConcurrentReferenceHashMap;

// 创建高并发场景下的引用Map (类似WeakHashMap但线程安全)

Map<String, Object> cache = new ConcurrentReferenceHashMap<>();

cache.put("key1", new LargeObject());

反射和类处理工具

7.ReflectionUtils

import org.springframework.util.ReflectionUtils;

// 获取类的字段

Field field = ReflectionUtils.findField(Person.class, "name");

ReflectionUtils.makeAccessible(field);

ReflectionUtils.setField(field, person, "John");

// 调用方法

Method method = ReflectionUtils.findMethod(Person.class, "setAge", int.class);

ReflectionUtils.makeAccessible(method);

ReflectionUtils.invokeMethod(method, person, 30);

// 字段回调

ReflectionUtils.doWithFields(Person.class, field -> {

System.out.println(field.getName());

});

8.ClassUtils

import org.springframework.util.ClassUtils;

// 获取类名

String shortName = ClassUtils.getShortName("org.example.MyClass"); // "MyClass"

// 检查类是否存在

boolean exists = ClassUtils.isPresent("java.util.List", null); // true

// 获取所有接口

Class<?>[] interfaces = ClassUtils.getAllInterfaces(ArrayList.class);

// 获取用户定义的类加载器

ClassLoader classLoader = ClassUtils.getDefaultClassLoader();

9.BeanUtils

import org.springframework.beans.BeanUtils;

// 复制属性

Person source = new Person("John", 30);

Person target = new Person();

BeanUtils.copyProperties(source, target);

// 实例化类

Person newPerson = BeanUtils.instantiateClass(Person.class);

// 查找方法

Method method = BeanUtils.findMethod(Person.class, "setName", String.class);

I/O和资源工具

10.FileCopyUtils

import org.springframework.util.FileCopyUtils;

// 复制文件内容

byte[] bytes = FileCopyUtils.copyToByteArray(new File("input.txt"));

FileCopyUtils.copy(bytes, new File("output.txt"));

// 读取文本

String content = FileCopyUtils.copyToString(

new InputStreamReader(new FileInputStream("input.txt"), "UTF-8"));

// 流复制

FileCopyUtils.copy(inputStream, outputStream);

Web相关工具类

11. WebUtils

import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;

// 获取Cookie

Cookie cookie = WebUtils.getCookie(request, "sessionId");

// 获取请求路径

String path = WebUtils.getLookupPathForRequest(request);

// 从请求中获取参数

int pageSize = WebUtils.getIntParameter(request, "pageSize", 10);

12.UriUtils

import org.springframework.web.util.UriUtils;

// 编解码URI组件

String encoded = UriUtils.encodePathSegment("path with spaces", "UTF-8");

String decoded = UriUtils.decode(encoded, "UTF-8");

验证和断言工具

13.Assert

import org.springframework.util.Assert;

// 常用断言

Assert.notNull(object, "Object must not be null");

Assert.hasText(name, "Name must not be empty");

Assert.isTrue(amount > 0, "Amount must be positive");

Assert.notEmpty(items, "Items must not be empty");

Assert.state(isInitialized, "Service is not initialized");

14.ObjectUtils

import org.springframework.util.ObjectUtils;

// 对象工具

boolean isEmpty = ObjectUtils.isEmpty(null); // true

boolean isEmpty2 = ObjectUtils.isEmpty(new String[0]); // true

String nullSafe = ObjectUtils.nullSafeToString(null); // "null"

boolean equals = ObjectUtils.nullSafeEquals(obj1, obj2);

// 默认值

String value = ObjectUtils.getOrDefault(null, "default");

15. NumberUtils

import org.springframework.util.NumberUtils;

// 数字转换

Integer parsed = NumberUtils.parseNumber("42", Integer.class);

Double converted = NumberUtils.convertNumberToTargetClass(42, Double.class);

日期和时间工具

16.DateTimeUtils

import org.springframework.format.datetime.DateTimeFormatUtils;

import java.util.Date;

// 格式化日期

String formatted = DateTimeFormatUtils.getDateTimeInstance().format(new Date());

17.StopWatch

import org.springframework.util.StopWatch;

// 计时工具

StopWatch watch = new StopWatch("TaskName");

watch.start("phase1");

// 执行任务1

Thread.sleep(100);

watch.stop();

watch.start("phase2");

// 执行任务2

Thread.sleep(200);

watch.stop();

// 输出报告

System.out.println(watch.prettyPrint());

System.out.println("Total time: " + watch.getTotalTimeMillis() + "ms");

安全相关工具

18.Base64Utils

import org.springframework.util.Base64Utils;

// Base64编解码

byte[] data = "Hello World".getBytes();

String encoded = Base64Utils.encodeToString(data);

byte[] decoded = Base64Utils.decodeFromString(encoded);

JSON和数据转换工具

19.JsonUtils

import org.springframework.boot.json.JsonParser;

import org.springframework.boot.json.JsonParserFactory;

// JSON解析

JsonParser parser = JsonParserFactory.getJsonParser();

Map<String, Object> parsed = parser.parseMap("{"name":"John", "age":30}");

List<Object> parsedList = parser.parseList("[1, 2, 3]");

总结

这些工具类涵盖了Java开发中的大部分常见场景,从基础的字符串处理到高级的反射操作,从文件IO到安全加密,从Web开发到性能监控。熟练掌握这些工具类可以显著提高开发效率,减少样板代码。

相关推荐

Python入门学习记录之一:变量_python怎么用变量

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

python变量命名规则——来自小白的总结

python是一个动态编译类编程语言,所以程序在运行前不需要如C语言的先行编译动作,因此也只有在程序运行过程中才能发现程序的问题。基于此,python的变量就有一定的命名规范。python作为当前热门...

Python入门学习教程:第 2 章 变量与数据类型

2.1什么是变量?在编程中,变量就像一个存放数据的容器,它可以存储各种信息,并且这些信息可以被读取和修改。想象一下,变量就如同我们生活中的盒子,你可以把东西放进去,也可以随时拿出来看看,甚至可以换成...

绘制学术论文中的“三线表”具体指导

在科研过程中,大家用到最多的可能就是“三线表”。“三线表”,一般主要由三条横线构成,当然在变量名栏里也可以拆分单元格,出现更多的线。更重要的是,“三线表”也是一种数据记录规范,以“三线表”形式记录的数...

Python基础语法知识--变量和数据类型

学习Python中的变量和数据类型至关重要,因为它们构成了Python编程的基石。以下是帮助您了解Python中的变量和数据类型的分步指南:1.变量:变量在Python中用于存储数据值。它们充...

一文搞懂 Python 中的所有标点符号

反引号`无任何作用。传说Python3中它被移除是因为和单引号字符'太相似。波浪号~(按位取反符号)~被称为取反或补码运算符。它放在我们想要取反的对象前面。如果放在一个整数n...

Python变量类型和运算符_python中变量的含义

别再被小名词坑哭了:Python新手常犯的那些隐蔽错误,我用同事的真实bug拆给你看我记得有一次和同事张姐一起追查一个看似随机崩溃的脚本,最后发现罪魁祸首竟然是她把变量命名成了list。说实话...

从零开始:深入剖析 Spring Boot3 中配置文件的加载顺序

在当今的互联网软件开发领域,SpringBoot无疑是最为热门和广泛应用的框架之一。它以其强大的功能、便捷的开发体验,极大地提升了开发效率,成为众多开发者构建Web应用程序的首选。而在Spr...

Python中下划线 ‘_’ 的用法,你知道几种

Python中下划线()是一个有特殊含义和用途的符号,它可以用来表示以下几种情况:1在解释器中,下划线(_)表示上一个表达式的值,可以用来进行快速计算或测试。例如:>>>2+...

解锁Shell编程:变量_shell $变量

引言:开启Shell编程大门Shell作为用户与Linux内核之间的桥梁,为我们提供了强大的命令行交互方式。它不仅能执行简单的文件操作、进程管理,还能通过编写脚本实现复杂的自动化任务。无论是...

一文学会Python的变量命名规则!_python的变量命名有哪些要求

目录1.变量的命名原则3.内置函数尽量不要做变量4.删除变量和垃圾回收机制5.结语1.变量的命名原则①由英文字母、_(下划线)、或中文开头②变量名称只能由英文字母、数字、下画线或中文字所组成。③英文字...

更可靠的Rust-语法篇-区分语句/表达式,略览if/loop/while/for

src/main.rs://函数定义fnadd(a:i32,b:i32)->i32{a+b//末尾表达式}fnmain(){leta:i3...

C++第五课:变量的命名规则_c++中变量的命名规则

变量的命名不是想怎么起就怎么起的,而是有一套固定的规则的。具体规则:1.名字要合法:变量名必须是由字母、数字或下划线组成。例如:a,a1,a_1。2.开头不能是数字。例如:可以a1,但不能起1a。3....

Rust编程-核心篇-不安全编程_rust安全性

Unsafe的必要性Rust的所有权系统和类型系统为我们提供了强大的安全保障,但在某些情况下,我们需要突破这些限制来:与C代码交互实现底层系统编程优化性能关键代码实现某些编译器无法验证的安全操作Rus...

探秘 Python 内存管理:背后的神奇机制

在编程的世界里,内存管理就如同幕后的精密操控者,确保程序的高效运行。Python作为一种广泛使用的编程语言,其内存管理机制既巧妙又复杂,为开发者们提供了便利的同时,也展现了强大的底层控制能力。一、P...