李锋镝的博客

  • 首页
  • 时间轴
  • 说说
  • 每日心情
  • Now
  • 系列文章
  • 论坛
  • 左邻右舍
    • 左邻右舍
    • 博友圈
  • 留言
    • 留言
    • 走心评论
  • 关于
    • 关于本站
    • 网站地图
    • 网站统计
    • 另一个网站
    • 我的导航站
    • 赞助
  • 🚇开往
!Destiny
惟坚韧者始能遂其志
  1. 首页
  2. 原创
  3. 正文

SpringBoot 中内置的 49 个常用工具类

2025年5月26日 约 1,672 字6 分钟 155 0 0
本文最后更新于 2025年5月26日,距今已 476 天,其中的信息可能已经发生变化,请注意甄别。

SpringBootBoot及其依赖的Spring框架还包含大量实用工具类,它们可以显著简化日常开发工作。本文将介绍49个常用工具类,并通过简洁的代码示例展示它们的基本用法。

字符串处理工具类

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. PropertyPlaceholderHelper

import org.springframework.util.PropertyPlaceholderHelper;  

PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");  
Properties props = new Properties();  
props.setProperty("name", "World");  
props.setProperty("greeting", "Hello ${name}!");  

String result = helper.replacePlaceholders("${greeting}", props::getProperty);  
// "Hello World!"  

集合和数组工具类

5. 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);  

6. 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]  

7. ConcurrentReferenceHashMap

import org.springframework.util.ConcurrentReferenceHashMap;  

// 创建高并发场景下的引用Map (类似WeakHashMap但线程安全)  
Map<String, Object> cache = new ConcurrentReferenceHashMap<>();  
cache.put("key1", new LargeObject());  

8. SystemPropertyUtils

import org.springframework.util.SystemPropertyUtils;  

// 解析含系统属性的字符串  
String javaHome = SystemPropertyUtils.resolvePlaceholders("${java.home}");  
String pathWithDefault = SystemPropertyUtils.resolvePlaceholders(  
    "${unknown.property:default}");  // "default"  

反射和类处理工具类

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

10. 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();  

11. MethodInvoker

import org.springframework.util.MethodInvoker;  

MethodInvoker invoker = new MethodInvoker();  
invoker.setTargetObject(new MyService());  
invoker.setTargetMethod("calculateTotal");  
invoker.setArguments(new Object[]{100, 0.2});  
invoker.prepare();  
Object result = invoker.invoke();  

12. 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和资源工具类

13. 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);  

14. ResourceUtils

import org.springframework.util.ResourceUtils;  

// 获取文件  
File file = ResourceUtils.getFile("classpath:config.properties");  

// 检查是否是URL  
boolean isUrl = ResourceUtils.isUrl("http://example.com");  

// 获取URL  
URL url = ResourceUtils.getURL("classpath:data.json");  

15. StreamUtils

import org.springframework.util.StreamUtils;  

// 流操作  
byte[] data = StreamUtils.copyToByteArray(inputStream);  
String text = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);  
StreamUtils.copy(inputStream, outputStream);  
StreamUtils.copy("Hello", StandardCharsets.UTF_8, outputStream);  

16. FileSystemUtils

import org.springframework.util.FileSystemUtils;  

// 删除目录  
boolean deleted = FileSystemUtils.deleteRecursively(new File("/tmp/test"));  

// 复制目录  
FileSystemUtils.copyRecursively(new File("source"), new File("target"));  

17. ResourcePatternUtils

import org.springframework.core.io.Resource;  
import org.springframework.core.io.support.ResourcePatternUtils;  
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;  

// 获取匹配资源  
Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(  
    new PathMatchingResourcePatternResolver())  
    .getResources("classpath*:META-INF/*.xml");  

Web相关工具类

18. 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);  

19. UriUtils

import org.springframework.web.util.UriUtils;  

// 编解码URI组件  
String encoded = UriUtils.encodePathSegment("path with spaces", "UTF-8");  
String decoded = UriUtils.decode(encoded, "UTF-8");  

20. UriComponentsBuilder

import org.springframework.web.util.UriComponentsBuilder;  

// 构建URI  
URI uri = UriComponentsBuilder.fromHttpUrl("http://example.com")  
    .path("/products")  
    .queryParam("category", "books")  
    .queryParam("sort", "price")  
    .build()  
    .toUri();  

21. ContentCachingRequestWrapper

import org.springframework.web.util.ContentCachingRequestWrapper;  
import javax.servlet.http.HttpServletRequest;  

ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);  
// 请求处理后  
byte[] body = wrapper.getContentAsByteArray();  

22. HtmlUtils

import org.springframework.web.util.HtmlUtils;  

// HTML转义  
String escaped = HtmlUtils.htmlEscape("<script>alert('XSS')</script>");  
// <script>alert('XSS')</script>  

// HTML反转义  
String unescaped = HtmlUtils.htmlUnescape("<b>Bold</b>");  
// <b>Bold</b>  

验证和断言工具类

23. 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");  

24. 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");  

25. NumberUtils

import org.springframework.util.NumberUtils;  

// 数字转换  
Integer parsed = NumberUtils.parseNumber("42", Integer.class);  
Double converted = NumberUtils.convertNumberToTargetClass(42, Double.class);  

日期和时间工具类

26. DateTimeUtils

import org.springframework.format.datetime.DateTimeFormatUtils;  
import java.util.Date;  

// 格式化日期  
String formatted = DateTimeFormatUtils.getDateTimeInstance().format(new Date());  

27. 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");  

安全相关工具类

28. DigestUtils

import org.springframework.util.DigestUtils;  

// MD5哈希  
String md5 = DigestUtils.md5DigestAsHex("password".getBytes());  

// 文件MD5  
String fileMd5;  
try (InputStream is = new FileInputStream("file.txt")) {  
    fileMd5 = DigestUtils.md5DigestAsHex(is);  
}  

29. Base64Utils

import org.springframework.util.Base64Utils;  

// Base64编解码  
byte[] data = "Hello World".getBytes();  
String encoded = Base64Utils.encodeToString(data);  
byte[] decoded = Base64Utils.decodeFromString(encoded);  

30. CryptoUtils

import org.springframework.security.crypto.encrypt.Encryptors;  
import org.springframework.security.crypto.encrypt.TextEncryptor;  

// 文本加密  
String password = "secret";  
String salt = "deadbeef";  
TextEncryptor encryptor = Encryptors.text(password, salt);  
String encrypted = encryptor.encrypt("Message");  
String decrypted = encryptor.decrypt(encrypted);  

JSON和数据转换工具类

31. 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]");  

32. TypeUtils

import org.springframework.core.ResolvableType;  

// 类型解析  
ResolvableType type = ResolvableType.forClass(List.class);  
ResolvableType elementType = type.getGeneric(0);  

// 泛型类型处理  
ResolvableType mapType = ResolvableType.forClassWithGenerics(  
    Map.class, String.class, Integer.class);  

33. MappingJackson2HttpMessageConverter

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;  
import com.fasterxml.jackson.databind.ObjectMapper;  

// 自定义JSON转换器  
ObjectMapper mapper = new ObjectMapper();  
// 配置mapper  
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);  

其他实用工具类

34. RandomStringUtils

import org.apache.commons.lang3.RandomStringUtils;  

// 随机字符串生成  
String random = RandomStringUtils.randomAlphanumeric(10);  
String randomLetters = RandomStringUtils.randomAlphabetic(8);  
String randomNumeric = RandomStringUtils.randomNumeric(6);  

35. CompletableFutureUtils

import java.util.concurrent.CompletableFuture;  
import java.util.List;  
import java.util.stream.Collectors;  

// 合并多个CompletableFuture结果  
List<CompletableFuture<String>> futures = /* 多个异步操作 */;  
CompletableFuture<List<String>> allResults = CompletableFuture.allOf(  
    futures.toArray(new CompletableFuture[0]))  
    .thenApply(v -> futures.stream()  
        .map(CompletableFuture::join)  
        .collect(Collectors.toList()));  

36. CacheControl

import org.springframework.http.CacheControl;  
import java.util.concurrent.TimeUnit;  

// 缓存控制  
CacheControl cacheControl = CacheControl.maxAge(1, TimeUnit.HOURS)  
    .noTransform()  
    .mustRevalidate();  

String headerValue = cacheControl.getHeaderValue();  

37. AnnotationUtils

import org.springframework.core.annotation.AnnotationUtils;  

// 查找注解  
Component annotation = AnnotationUtils.findAnnotation(MyClass.class, Component.class);  

// 获取注解属性  
String value = AnnotationUtils.getValue(annotation, "value").toString();  

// 合并注解  
Component mergedAnnotation = AnnotationUtils.synthesizeAnnotation(  
    annotation, MyClass.class);  

38. DefaultConversionService

import org.springframework.core.convert.support.DefaultConversionService;  

// 类型转换  
DefaultConversionService conversionService = new DefaultConversionService();  
String strValue = "42";  
Integer intValue = conversionService.convert(strValue, Integer.class);  

39. HeaderUtils

import org.springframework.http.HttpHeaders;  

// HTTP头处理  
HttpHeaders headers = new HttpHeaders();  
headers.add("Content-Type", "application/json");  
headers.setContentLength(1024);  
headers.setCacheControl("max-age=3600");  

40. MediaTypeFactory

import org.springframework.http.MediaType;  
import org.springframework.http.MediaTypeFactory;  
import java.util.Optional;  

// 根据文件名推断媒体类型  
Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("document.pdf");  
// application/pdf  

41. MimeTypeUtils

import org.springframework.util.MimeTypeUtils;  

// MIME类型常量和解析  
boolean isCompatible = MimeTypeUtils.APPLICATION_JSON.isCompatibleWith(  
    MimeTypeUtils.APPLICATION_JSON_UTF8);  

42. WebClient

import org.springframework.web.reactive.function.client.WebClient;  
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;  

// 创建WebClient  
WebClient webClient = WebClient.builder()  
    .baseUrl("https://api.example.com")  
    .defaultHeader("Authorization", "Bearer token")  
    .filter(ExchangeFilterFunction.ofRequestProcessor(  
        clientRequest -> {  
            // 请求处理  
            return Mono.just(clientRequest);  
        }))  
    .build();  

43. PropertySource

import org.springframework.core.env.PropertySource;  
import org.springframework.core.env.StandardEnvironment;  

// 添加属性源  
StandardEnvironment env = new StandardEnvironment();  
Map<String, Object> map = new HashMap<>();  
map.put("app.name", "MyApp");  
env.getPropertySources().addFirst(new MapPropertySource("my-properties", map));  

44. ApplicationEventPublisher

import org.springframework.context.ApplicationEventPublisher;  

// 发布事件  
ApplicationEventPublisher publisher = /* 获取发布器 */;  
publisher.publishEvent(new CustomEvent("Something happened"));  

45. LocaleContextHolder

import org.springframework.context.i18n.LocaleContextHolder;  
import java.util.Locale;  

// 获取/设置当前语言环境  
Locale currentLocale = LocaleContextHolder.getLocale();  
LocaleContextHolder.setLocale(Locale.FRENCH);  

46. AopUtils

import org.springframework.aop.support.AopUtils;  

// AOP工具方法  
boolean isAopProxy = AopUtils.isAopProxy(bean);  
boolean isCglibProxy = AopUtils.isCglibProxy(bean);  
Class<?> targetClass = AopUtils.getTargetClass(bean);  

47. ProxyFactory

import org.springframework.aop.framework.ProxyFactory;  

// 创建代理  
ProxyFactory factory = new ProxyFactory(targetObject);  
factory.addInterface(MyInterface.class);  
factory.addAdvice(new MyMethodInterceptor());  
MyInterface proxy = (MyInterface) factory.getProxy();  

48. ClassPathScanningCandidateComponentProvider

import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;  

// 扫描类路径  
ClassPathScanningCandidateComponentProvider scanner =  
    new ClassPathScanningCandidateComponentProvider(true);  
scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));  
Set<BeanDefinition> beans = scanner.findCandidateComponents("org.example");  

49. YamlPropertiesFactoryBean

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;  
import org.springframework.core.io.ClassPathResource;  

// 解析YAML文件  
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();  
yaml.setResources(new ClassPathResource("application.yml"));  
Properties properties = yaml.getObject();  
除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.lifengdi.com/article/4430

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
分享到

SpringBoot 中内置的 49 个常用工具类

也可使用浏览器菜单中的「分享」功能

微信扫一扫分享

标签: JAVA Spring SpringBoot 工具类
最后更新:2025年5月26日
相关文章
  • Java并发编程之如何保证线程顺序执行2021年5月18日
  • SpringBoot集成Redis,从Redis中获取数据为null,但实际上Redis中是存在对应的数据的,是什么原因导致的呢?2021年1月19日
  • @Valid 和 @Validated 的区别2025年5月23日
  • Java SPI详解2021年4月16日
  • JVM内存结构详解2019年10月18日

李锋镝

既然选择了远方,便只顾风雨兼程。

打赏 点赞
< 上一篇
下一篇 >
1234567891112131415161718192021222324252627282930313233343536373839404142434446474849505152535455575859606162636465666769727476777879808182858687909293949596979899
取消回复

文章评论

还没有评论,快来抢沙发吧~

惟坚韧者始能遂其志。

听点儿音乐吧 朋友~
文章目录
最新 热点 随机
最新 热点 随机
支撑全网40%网站的WordPress正在重新拥抱PHP生态 Kratos-plus v1.1.24版本更新说明 关于主题加载速度优化的一点儿小演进 市场主流AI编程大模型横向深度分析(2026-09-11) 一款节省token的利器:RTK(Rust Token Killer) RAG太难学?LLM Wiki了解一下
给主题增加了Now、每日心情、年度回顾、岁月同一天、随机漫步等功能WordPress缓存插件WP Fastest Cache、WP Rocket 、FlyingPress对比关于使用AI的一些思考Kratos+ v1.1.16版本更新说明AI时代,个人技术博客的出路在哪里?推荐一个SVG 矢量小图标免费下载网站
Springboot接入DeepSeek API 详解 ZooKeeper 数据持久化 重构 Controller 终极指南:从臃肿到优雅的 7 大黄金法则 + 实战技巧 UUID太长怎么办?快来试试NanoId 写了个日期进度条的小插件 JMX监控权限认证配置
最近评论
blank
lijie blog 发布于 9 小时前(09月14日) 友链申请 名称:lijie blog 链接:https://lijie.cool 描述:懒于当...
blank
Hary 发布于 11 小时前(09月14日) 等PHP9推倒重来,出个船新版本
blank
李锋镝 发布于 23 小时前(09月14日) 不愧是皮总,这措辞~ :30:
blank
皮皮社长 发布于 23 小时前(09月14日) :20: 我勒了个去,中国汉字波大精深。 :42:
blank
李锋镝 发布于 23 小时前(09月14日) 我这里面也带了一堆小表情包,看看不行也优化一波
标签聚合
Redis WordPress AI SpringBoot Claude 架构 JAVA 分布式 AI编程 K8s ElasticSearch Spring 多线程 日常 IDEA MySQL MQ JVM SQL 数据库
友情链接
  • 若梦博客
  • 九仞之行
  • sssr7844的博客
  • Honesty
  • 彬红茶日记
  • 蜗牛工作室
  • 老张博客
  • 搬砖日记
  • 瓦匠个人小站
  • 志文工作室
  • 韩情脉脉
  • 知向前端
  • Serendipity
  • 临窗旋墨
  • 韩小韩博客
  • 皮皮社
  • 哥斯拉
  • Mr.Sun的博客
  • 懋和道人
  • 林羽凡

COPYRIGHT © 2016-2026 lifengdi.com. ALL RIGHTS RESERVED.

Domain age badge for lifengdi.com

Theme Kratos-plus By Dylan Li

津ICP备2024022503号-3

京公网安备11011502039375号