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

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

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

前言:

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开发到性能监控。熟练掌握这些工具类可以显著提高开发效率,减少样板代码。

相关推荐

Opinion丨Struggle Against U.S. Mind colonization in the Global South

Editor'snote:Thismonth,XinhuaNewsAgency'sThinkTankreleasedareporttitled"Colonizationof...

爱可可AI论文推介(2020.11.4)_爱可可女装旗舰店

LG-机器学习CV-计算机视觉CL-计算与语言AS-音频与语音RO-机器人(*表示值得重点关注)1、[LG]*CombiningLabelPropagationan...

何新:罗马伪史考英文版序言_罗马史学

2019-10-2514:48:27何新:罗马伪史考序言(英文译本)HeXin:PreambleofResearchonPseudo-historyofRome1Afewyear...

XPeng Stock Rises Over 4% after Q2 Revenue and EV Margin Set Records

TMTPOST--TheAmericandepositaryreceipts(ADRs)ofXPengInc.rosearound4.2%onTuesdayaftert...

英汉世界语部首(八)_英文部首字典

本节讲八个部首,分别是:弓gōng【ECWLrad】bow廾gǒng【ECWLrad】twen广guǎng【ECWLrad】vast己jǐ【ECWLrad】self已yǐ...

一课译词:划水_划水是什么地方的方言

[Photo/SIPA]懒惰是人类的天性,因此才总有人会在工作时“划水”。“划水【huáshuǐ】”,本意是指“用胳膊划的动作(makestrokeswithone’sarms)”,延伸为“...

首测!GPT-4o做Code Review可行吗?

编辑|言征出品|51CTO技术栈(微信号:blog51cto)近日,OpenAI一记重拳,推出了GPT-4o(“o”表示“omni”),将语音识别和对话方面的优势展示的淋漓尽致。几乎可以肯定,...

C++|漫谈STL细节及内部原理_c++ stl详解

1988年,AlexanderStepanov开始进入惠普的PaloAlto实验室工作,在随后的4年中,他从事的是有关磁盘驱动器方面的工作。直到1992年,由于参加并主持了实验室主任BillWo...

C++ inline关键字深度解析:不止于优化的头文件定义许可

在C++开发中,几乎每个程序员都用过inline关键字,但多数人只停留在“内联优化”的表层理解。事实上,inline的真正威力在于它打破了C++的单一定义规则(ODR)限制,成为头文件中安全定义函数的...

实用 | 10分钟教你搭建一个嵌入式web服务器

之前分享的文章中提到了几种可以在嵌入式中使用的web服务器。嵌入式web服务器就是把web服务器移植到嵌入式系统的服务器。它仍然是基于http文本协议进行通信的,具有标准的接口形式,对客户端...

中间语言格式_中间格式文本是什么

在通常情况下,编译器会将目标语言转换成某种中间语言格式,而不是直接将源代码转换成二进制机器指令,不少c语言编译器,都会将代码编译成汇编语言,然后再通过汇编语言编译器将汇编代码转换成目标机器可执行的二进...

一线开发大牛带你深度解析探讨模板解释器,解释器的生成

解释器生成解释器的机器代码片段都是在TemplateInterpreterGenerator::generate_all()中生成的,下面将分小节详细展示该函数的具体细节,以及解释器某个组件的机器代码...

干货,Web开发和前端开发逆天工具大全

微信ID:WEB_wysj(点击关注)◎◎◎◎◎◎◎◎◎一┳═┻︻▄(点击页底“阅读原文”前往下载)●●●逆天工具CDN资源库国内Bootstrap中文网开源项目免费CDN服务36...

移动端rem+vw适配_移动端web页面适配方案

rem:rem是相对单位,设置根元素html的font-size,比如给html设置字体大小为100px,1rem=100px;rem缺点:1.和根元素font-size值强耦合,系统字...

从零搭建 React 开发 H5 模板_react html5

项目创建创建项目文件夹mkdir react-democd react-demonpm init -y依赖安装yarn add rea...