SpringBoot中StringUtils工具类的使用
SpringBoot 项目中,StringUtils
是一个高频使用的工具类,它极大地简化了字符串操作。主要有两个来源:Spring Framework 自带的 org.springframework.util.StringUtils
和 Apache Commons Lang 3 提供的 org.apache.commons.lang3.StringUtils
。它们各有侧重,下面这个表格能帮你快速了解它们的核心区别和常用方法。
特性 | Spring Framework StringUtils | Apache Commons Lang3 StringUtils |
---|---|---|
核心区别 | 提供 Spring 生态基础字符串操作,满足日常开发 | 功能极其全面,几乎覆盖所有字符串处理场景 |
空值判断 |
|
|
检查内容 |
|
|
大小写处理 |
|
|
修剪操作 |
|
|
替换与删除 |
|
|
拆分与拼接 |
|
|
其他实用功能 |
|
|
一、如何选择与使用
选择依据:如果你的项目是纯粹的 SpringBoot 应用,进行基本的字符串判断和操作,Spring Framework 自带的
StringUtils
通常就够了,无需引入额外依赖。如果你需要进行更复杂的字符串处理,如数字判断、随机字符串生成、复杂的截取和格式化等,那么 Apache Commons Lang3 是更强大的选择。依赖引入:使用 Apache Commons Lang3 需要在
pom.xml
中添加依赖。<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version> <!-- 请使用最新版本 --> </dependency>
核心方法辨析:理解关键方法的细微差别非常重要,尤其是在处理空字符串和空白符时。
isEmpty
vsisBlank
:这是最容易混淆的一点。isEmpty
只检查null
和长度为零,而isBlank
还会将纯空白字符(如空格、制表符)视为“空”。例如,对于字符串" "
,isEmpty
返回false
,而isBlank
返回true
。
hasLength
vshasText
:Spring 中的hasLength
等价于!isEmpty
,即不为 null 且长度大于零。而hasText
要求更严格,字符串必须包含非空白字符。例如," "
能通过hasLength
检查,但无法通过hasText
检查。方法
描述
null
""
" "
"a"
" a "
isEmpty(str)
仅判断是否为
null
或 空字符串✅
✅
❌
❌
❌
isBlank(str)
判断是否为
null
、空字符串或 纯空白字符✅
✅
✅
❌
❌
简单记忆:
用
isBlank()
来验证用户输入(如表单字段),因为用户可能只输入空格。用
isEmpty()
来检查明确的空值或空字符串。
二、常用方法分类总结
1. 空值 & 空白检查
// 检查空值或空白
StringUtils.isBlank(null); // true
StringUtils.isBlank(""); // true
StringUtils.isBlank(" "); // true// 反向检查
StringUtils.isNotBlank(" hello "); // true// 仅检查空值或空字符串
StringUtils.isEmpty(" "); // false
StringUtils.isNotEmpty(" "); // true
2. 修剪与清理
// 修剪首尾空格(类似JDK的trim,但null安全)
StringUtils.trim(null); // null
StringUtils.trim(" hello "); // "hello"// 修剪首尾空白(包括Unicode空白符,比trim更强大)
StringUtils.strip(" hello "); // "hello"// 删除所有空格
StringUtils.deleteWhitespace(" h e l l o "); // "hello"
3. 大小写转换与首字母处理
// 首字母大写
StringUtils.capitalize("hello"); // "Hello"// 首字母小写
StringUtils.uncapitalize("Hello"); // "hello"// 全大写/全小写(null安全)
StringUtils.upperCase("Hello"); // "HELLO"
StringUtils.lowerCase("Hello"); // "hello"
4. 比较与包含判断
// 安全比较(可处理null值)
StringUtils.equals(null, null); // true
StringUtils.equals("abc", "ABC"); // false// 忽略大小写比较
StringUtils.equalsIgnoreCase("abc", "ABC"); // true// 判断包含关系(null安全)
StringUtils.contains("hello world", "wor"); // true
StringUtils.containsIgnoreCase("Hello World", "hello"); // true
5. 截取与拆分
// 安全截取子串
StringUtils.substring("hello world", 0, 5); // "hello"// 拆分字符串
String[] parts = StringUtils.split("a,b,c", ","); // ["a", "b", "c"]// 拆分并限制结果数量
String[] parts2 = StringUtils.split("a:b:c:d", ":", 2); // ["a", "b:c:d"]
6. 拼接与连接
// 连接数组或集合
StringUtils.join(new String[]{"a", "b", "c"}, ","); // "a,b,c"// 连接时处理null元素
StringUtils.join(new String[]{"a", null, "c"}, "-"); // "a--c"
7. 替换与删除
// 替换所有匹配项
StringUtils.replace("aba", "a", "z"); // "zbz"// 替换每次匹配项
StringUtils.replaceEach("abcde", new String[]{"a", "c"}, new String[]{"x", "y"}); // "xbyde"// 删除所有匹配项
StringUtils.remove("hello world", "o"); // "hell wrld"
8. 其他实用工具
// 重复字符串
StringUtils.repeat("ab", 3); // "ababab"// 反转字符串
StringUtils.reverse("hello"); // "olleh"// 计算匹配次数
StringUtils.countMatches("abracadabra", "a"); // 5// 获取字符串长度(null安全)
StringUtils.length(null); // 0
三、最佳实践与示例
1.用户输入验证
public void processUserInput(String input) {if (StringUtils.isBlank(input)) {throw new IllegalArgumentException("输入不能为空");}// 处理输入String cleanedInput = StringUtils.strip(input);
}
2.安全处理字符串操作
// 避免NullPointerException
String result = StringUtils.defaultString(possibleNullString, "default");// 安全比较
if (StringUtils.equals(userInput, expectedValue)) {// 执行操作
}
3.高效字符串处理
// 构建路径(避免开头多余的分隔符)
String path = StringUtils.joinWith("/", "", "usr", "local", "bin"); // "/usr/local/bin"// 处理CSV数据
String[] values = StringUtils.split(csvLine, ",", -1);
四、扩展技巧
1.链式操作:结合多个方法完成复杂处理
String processed = StringUtils.capitalize(StringUtils.strip(StringUtils.remove(userInput, "\n")));
2.与Java 8 Stream API结合使用
List<String> filtered = strings.stream().filter(StringUtils::isNotBlank).map(StringUtils::trim).collect(Collectors.toList());
3.自定义扩展(如示例中的扩展类):
添加项目特定的字符串处理逻辑
封装常用模式
提供更语义化的方法名