SpringBoot 内置的 20 个高效工具类

Spring Boot 内置了许多高效的 Spring Framework 工具类,以下是 20 个常用且高效的实用工具类,涵盖字符串处理、集合操作、资源访问、反射工具等多个方面:

一、字符串与文本处理

1. StringUtils (org.springframework.util)

java 复制代码
// 避免空指针的字符串操作
StringUtils.hasText(str);     // 检查是否有实际内容(非null/非空/非空白)
StringUtils.isEmpty(str);     // 是否为null或空字符串
StringUtils.trimWhitespace(str);
StringUtils.commaDelimitedListToStringArray(str);

2. ObjectUtils (org.springframework.util)

java 复制代码
// 安全的对象操作
ObjectUtils.nullSafeToString(obj);
ObjectUtils.isEmpty(obj);     // 检查数组、集合、Map、字符串等
ObjectUtils.nullSafeEquals(obj1, obj2);

二、集合与数组操作

3. CollectionUtils (org.springframework.util)

java 复制代码
// 集合工具
CollectionUtils.isEmpty(collection);
CollectionUtils.containsInstance(collection, element);
CollectionUtils.findFirstMatch(coll1, coll2);
CollectionUtils.mergePropertiesIntoMap(properties, map);

4. MultiValueMap (org.springframework.util)

java 复制代码
// 一键多值的Map实现
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key", "value1");
map.add("key", "value2");
List<String> values = map.get("key");

5. StreamUtils (org.springframework.util)

java 复制代码
// Stream操作工具
StreamUtils.copy(inputStream, outputStream);
StreamUtils.copyToString(inputStream, charset);
StreamUtils.copyToByteArray(inputStream);

三、资源访问

6. ResourceUtils (org.springframework.util)

java 复制代码
// 资源路径处理
ResourceUtils.getFile("classpath:config.yml");
ResourceUtils.isFileURL(url);
ResourceUtils.isJarURL(url);

7. FileCopyUtils (org.springframework.util)

java 复制代码
// 文件复制工具
FileCopyUtils.copy(File in, File out);
FileCopyUtils.copy(byte[] in, File out);
String content = FileCopyUtils.copyToString(new FileReader(file));

8. Resource (org.springframework.core.io)

java 复制代码
// 统一的资源抽象
Resource resource = new ClassPathResource("application.yml");
InputStream is = resource.getInputStream();
File file = resource.getFile();

四、反射与类操作

9. ReflectionUtils (org.springframework.util)

java 复制代码
// 反射工具,处理受检异常
ReflectionUtils.findField(clazz, fieldName);
ReflectionUtils.setField(field, target, value);
ReflectionUtils.invokeMethod(method, target, args);
ReflectionUtils.doWithFields(clazz, field -> {
    // 处理字段
});

10. ClassUtils (org.springframework.util)

java 复制代码
// 类相关工具
ClassUtils.getDefaultClassLoader();
ClassUtils.forName(className, classLoader);
ClassUtils.getAllInterfacesForClass(clazz);
ClassUtils.isPresent(className, classLoader); // 检查类是否存在

11. BeanUtils (org.springframework.beans)

java 复制代码
// Bean属性复制
BeanUtils.copyProperties(source, target);
PropertyValues pvs = BeanUtils.getPropertyDescriptors(target);
BeanUtils.instantiateClass(constructor, args);

五、系统与IO操作

12. SystemPropertyUtils (org.springframework.core.env)

java 复制代码
// 系统属性处理
SystemPropertyUtils.resolvePlaceholders(text);
// 解析 ${...} 占位符

13. SerializationUtils (org.springframework.util)

java 复制代码
// 序列化工具
byte[] bytes = SerializationUtils.serialize(obj);
Object obj = SerializationUtils.deserialize(bytes);
SerializationUtils.clone(obj);  // 深度克隆(对象需实现Serializable)

六、断言与校验

14. Assert (org.springframework.util)

java 复制代码
// 参数断言校验
Assert.notNull(obj, "对象不能为null");
Assert.hasText(str, "字符串必须有内容");
Assert.isTrue(expression, "表达式必须为true");
Assert.state(expression, "状态校验失败");

15. StopWatch (org.springframework.util)

java 复制代码
// 简单性能监控
StopWatch watch = new StopWatch("任务监控");
watch.start("任务1");
// ... 执行操作
watch.stop();
watch.start("任务2");
// ...
System.out.println(watch.prettyPrint());

七、其他实用工具

16. Base64Utils (org.springframework.util)

java 复制代码
// Base64编码解码
String encoded = Base64Utils.encodeToString(data.getBytes());
byte[] decoded = Base64Utils.decodeFromString(encoded);

17. DigestUtils (org.springframework.util)

java 复制代码
// 摘要工具(需要spring-core依赖)
String md5 = DigestUtils.md5DigestAsHex(bytes);
String sha256 = DigestUtils.sha256DigestAsHex(input);

18. AntPathMatcher (org.springframework.util)

java 复制代码
// Ant风格路径匹配
AntPathMatcher matcher = new AntPathMatcher();
matcher.match("/api/**/test", "/api/v1/user/test");
matcher.extractUriTemplateVariables("/{id}/detail", "/123/detail");

19. MimeTypeUtils (org.springframework.util)

java 复制代码
// MIME类型工具
MimeType mimeType = MimeTypeUtils.APPLICATION_JSON;
MimeTypeUtils.parseMimeType("application/json");
MimeTypeUtils.TEXT_PLAIN;

20. AopUtils (org.springframework.aop.support)

java 复制代码
// AOP相关工具
AopUtils.isAopProxy(obj);
AopUtils.isJdkDynamicProxy(obj);
AopUtils.isCglibProxy(obj);
AopUtils.getTargetClass(obj);

使用示例:综合工具类应用

java 复制代码
import org.springframework.util.*;

public class ExampleService {
    
    public void processData(String input) {
        // 1. 参数校验
        Assert.hasText(input, "输入不能为空");
        
        // 2. 字符串处理
        String trimmed = StringUtils.trimWhitespace(input);
        
        // 3. 反射操作
        ReflectionUtils.doWithFields(User.class, field -> {
            if (field.isAnnotationPresent(Valid.class)) {
                // 处理有Valid注解的字段
            }
        });
        
        // 4. 性能监控
        StopWatch watch = new StopWatch();
        watch.start("数据处理");
        // ... 业务逻辑
        watch.stop();
        log.info(watch.prettyPrint());
    }
}

最佳实践建议

  1. 优先使用Spring工具类:避免重复造轮子,Spring工具类经过充分测试
  2. 注意空安全:大多数Spring工具类都是空安全的
  3. 了解源码:复杂操作前查看工具类实现,确保理解其行为
  4. 组合使用:多个工具类可以组合解决复杂问题
  5. 版本兼容:注意不同Spring版本的工具类方法差异
相关推荐
我是小疯子662 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
森叶2 小时前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
二哈喇子!2 小时前
Eclipse中导入外部jar包
java·eclipse·jar
微露清风2 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
进阶小白猿3 小时前
Java技术八股学习Day20
java·开发语言·学习
gis开发3 小时前
【无标题】
java·前端·javascript
Wpa.wk3 小时前
性能测试 - 搭建线上的性能测试环境参考逻辑图
java·经验分享·测试工具·jmeter·性能测试
代码村新手3 小时前
C++-类和对象(中)
java·开发语言·c++
葵花楹3 小时前
【JAVA课设】【游戏社交系统】
java·开发语言·游戏