Spring Boot 3 内置工具类详解

什么是 Spring Boot 内置工具类

Spring Boot 3 提供了许多内置的工具类,这些工具类封装了常见的操作,简化了开发过程,提高了代码的可读性和可维护性。这些工具类涵盖了字符串处理、集合操作、时间日期处理、反射、Web 操作等多个方面。

字符串工具类

1. StringUtils

应用场景:字符串的判空、修剪、分割、替换等操作

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.springframework.util.StringUtils;

public class StringUtilsDemo {
public static void main(String[] args) {
// 判空操作
String str1 = null;
String str2 = "";
String str3 = " ";

System.out.println("str1 是否为空: " + StringUtils.isEmpty(str1)); // true
System.out.println("str2 是否为空: " + StringUtils.isEmpty(str2)); // true
System.out.println("str3 是否为空: " + StringUtils.isEmpty(str3)); // false
System.out.println("str3 是否为空白: " + StringUtils.isBlank(str3)); // true

// 修剪操作
String str4 = " Hello World ";
System.out.println("修剪后: " + StringUtils.trimWhitespace(str4)); // "Hello World"

// 分割操作
String str5 = "a,b,c,d";
String[] parts = StringUtils.split(str5, ",");
System.out.println("分割结果: " + Arrays.toString(parts)); // [a, b, c, d]

// 替换操作
String str6 = "Hello {name}";
String replaced = StringUtils.replace(str6, "{name}", "Spring Boot");
System.out.println("替换结果: " + replaced); // "Hello Spring Boot"

// 检查字符串是否以指定前缀开始
String str7 = "SpringBootApplication";
System.out.println("是否以Spring开头: " + StringUtils.startsWith(str7, "Spring")); // true

// 检查字符串是否以指定后缀结束
System.out.println("是否以Application结尾: " + StringUtils.endsWith(str7, "Application")); // true
}
}

2. ObjectUtils

应用场景:对象的判空、比较、转换等操作

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import org.springframework.util.ObjectUtils;

public class ObjectUtilsDemo {
public static void main(String[] args) {
// 判空操作
Object obj1 = null;
Object obj2 = new Object();

System.out.println("obj1 是否为空: " + ObjectUtils.isEmpty(obj1)); // true
System.out.println("obj2 是否为空: " + ObjectUtils.isEmpty(obj2)); // false

// 比较操作
Integer num1 = 10;
Integer num2 = 10;
Integer num3 = 20;

System.out.println("num1 和 num2 是否相等: " + ObjectUtils.nullSafeEquals(num1, num2)); // true
System.out.println("num1 和 num3 是否相等: " + ObjectUtils.nullSafeEquals(num1, num3)); // false

// 转换为字符串
Object obj3 = 123;
Object obj4 = null;

System.out.println("obj3 转换为字符串: " + ObjectUtils.nullSafeToString(obj3)); // "123"
System.out.println("obj4 转换为字符串: " + ObjectUtils.nullSafeToString(obj4)); // ""

// 获取对象的类名
System.out.println("obj2 的类名: " + ObjectUtils.getClassName(obj2)); // "java.lang.Object"
System.out.println("obj4 的类名: " + ObjectUtils.getClassName(obj4)); // "null"
}
}

集合工具类

1. CollectionUtils

应用场景:集合的判空、操作、转换等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class CollectionUtilsDemo {
public static void main(String[] args) {
// 判空操作
List<String> list1 = null;
List<String> list2 = new ArrayList<>();
List<String> list3 = List.of("a", "b", "c");

System.out.println("list1 是否为空: " + CollectionUtils.isEmpty(list1)); // true
System.out.println("list2 是否为空: " + CollectionUtils.isEmpty(list2)); // true
System.out.println("list3 是否为空: " + CollectionUtils.isEmpty(list3)); // false

// 合并集合
List<String> list4 = List.of("d", "e", "f");
List<String> mergedList = new ArrayList<>(list3);
CollectionUtils.mergeArrayIntoCollection(list4.toArray(), mergedList);
System.out.println("合并后的集合: " + mergedList); // [a, b, c, d, e, f]

// 检查集合是否包含指定元素
System.out.println("list3 是否包含a: " + CollectionUtils.contains(list3.iterator(), "a")); // true

// Map 操作
Map<String, String> map1 = null;
Map<String, String> map2 = new HashMap<>();
Map<String, String> map3 = Map.of("key1", "value1", "key2", "value2");

System.out.println("map1 是否为空: " + CollectionUtils.isEmpty(map1)); // true
System.out.println("map2 是否为空: " + CollectionUtils.isEmpty(map2)); // true
System.out.println("map3 是否为空: " + CollectionUtils.isEmpty(map3)); // false
}
}

2. ArrayUtils

应用场景:数组的判空、操作、转换等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import org.springframework.util.ArrayUtils;

public class ArrayUtilsDemo {
public static void main(String[] args) {
// 判空操作
String[] arr1 = null;
String[] arr2 = new String[0];
String[] arr3 = {"a", "b", "c"};

System.out.println("arr1 是否为空: " + ArrayUtils.isEmpty(arr1)); // true
System.out.println("arr2 是否为空: " + ArrayUtils.isEmpty(arr2)); // true
System.out.println("arr3 是否为空: " + ArrayUtils.isEmpty(arr3)); // false

// 合并数组
String[] arr4 = {"d", "e", "f"};
String[] mergedArray = ArrayUtils.addAll(arr3, arr4);
System.out.println("合并后的数组: " + Arrays.toString(mergedArray)); // [a, b, c, d, e, f]

// 查找元素索引
int index = ArrayUtils.indexOf(arr3, "b");
System.out.println("b 的索引: " + index); // 1

// 检查数组是否包含指定元素
System.out.println("arr3 是否包含c: " + ArrayUtils.contains(arr3, "c")); // true

// 数组转列表
List<String> list = Arrays.asList(arr3);
System.out.println("数组转列表: " + list); // [a, b, c]
}
}

时间日期工具类

1. DateTimeUtils

应用场景:日期时间的格式化、解析、计算等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import org.springframework.util.DateTimeUtils;
import java.util.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeUtilsDemo {
public static void main(String[] args) {
// 日期转字符串
Date date = new Date();
String dateStr = DateTimeUtils.formatDateTime(date);
System.out.println("日期转字符串: " + dateStr); // 格式: yyyy-MM-dd HH:mm:ss

// 时间戳转日期
long timestamp = System.currentTimeMillis();
Date dateFromTimestamp = new Date(timestamp);
System.out.println("时间戳转日期: " + DateTimeUtils.formatDateTime(dateFromTimestamp));

// Java 8 时间API示例
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println("LocalDateTime 格式化: " + formattedNow);

// 解析字符串为 LocalDateTime
String dateTimeStr = "2023-12-25 10:30:00";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeStr, formatter);
System.out.println("解析后的 LocalDateTime: " + parsedDateTime);
}
}

2. StopWatch

应用场景:性能测试、代码执行时间统计

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.springframework.util.StopWatch;

public class StopWatchDemo {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch("测试代码执行时间");

// 任务1
stopWatch.start("任务1");
Thread.sleep(1000);
stopWatch.stop();
System.out.println("任务1 执行时间: " + stopWatch.getLastTaskTimeMillis() + "ms");

// 任务2
stopWatch.start("任务2");
Thread.sleep(1500);
stopWatch.stop();
System.out.println("任务2 执行时间: " + stopWatch.getLastTaskTimeMillis() + "ms");

// 任务3
stopWatch.start("任务3");
Thread.sleep(500);
stopWatch.stop();
System.out.println("任务3 执行时间: " + stopWatch.getLastTaskTimeMillis() + "ms");

// 总执行时间
System.out.println("总执行时间: " + stopWatch.getTotalTimeMillis() + "ms");

// 打印详细信息
System.out.println("\n详细信息:");
System.out.println(stopWatch.prettyPrint());
}
}

反射工具类

1. ReflectionUtils

应用场景:反射操作,如获取方法、字段、调用方法等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Field;

public class ReflectionUtilsDemo {
public static void main(String[] args) {
// 获取类的方法
Method method = ReflectionUtils.findMethod(Person.class, "getName");
System.out.println("找到的方法: " + method.getName());

// 获取类的字段
Field field = ReflectionUtils.findField(Person.class, "name");
System.out.println("找到的字段: " + field.getName());

// 创建实例
Person person = new Person("张三", 25);

// 调用方法
String name = (String) ReflectionUtils.invokeMethod(method, person);
System.out.println("调用方法结果: " + name);

// 设置字段值
ReflectionUtils.setField(field, person, "李四");
System.out.println("设置字段后的值: " + person.getName());

// 获取字段值
Object ageField = ReflectionUtils.findField(Person.class, "age");
Integer age = (Integer) ReflectionUtils.getField(ageField, person);
System.out.println("获取字段值: " + age);
}

static class Person {
private String name;
private Integer age;

public Person(String name, Integer age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}
}

Web 相关工具类

1. WebUtils

应用场景:Web 应用中的请求、响应处理

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WebUtilsDemo {
// 在控制器中使用
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取会话属性
Object user = WebUtils.getSessionAttribute(request, "user");
System.out.println("会话中的用户: " + user);

// 设置会话属性
WebUtils.setSessionAttribute(request, "user", "新用户");

// 移除会话属性
WebUtils.removeSessionAttribute(request, "oldUser");

// 获取请求参数
String id = WebUtils.findParameterValue(request, "id");
System.out.println("请求参数id: " + id);

// 检查请求是否为ajax请求
boolean isAjax = WebUtils.isAjaxRequest(request);
System.out.println("是否为ajax请求: " + isAjax);

// 检查请求是否为multipart请求
boolean isMultipart = WebUtils.isMultipartRequest(request);
System.out.println("是否为multipart请求: " + isMultipart);
}
}

2. UriComponentsBuilder

应用场景:URL 的构建、解析、编码等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;

public class UriComponentsBuilderDemo {
public static void main(String[] args) {
// 构建URL
URI uri = UriComponentsBuilder
.fromHttpUrl("http://example.com/api")
.path("/users")
.queryParam("page", 1)
.queryParam("size", 10)
.queryParam("sort", "name,asc")
.build()
.toUri();

System.out.println("构建的URL: " + uri); // http://example.com/api/users?page=1&size=10&sort=name,asc

// 解析URL
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/api/users?id=123&name=test");
System.out.println("主机: " + builder.build().getHost()); // example.com
System.out.println("路径: " + builder.build().getPath()); // /api/users
System.out.println("查询参数: " + builder.build().getQuery()); // id=123&name=test
}
}

3. HtmlUtils

应用场景:HTML 的转义、unescape 等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.web.util.HtmlUtils;

public class HtmlUtilsDemo {
public static void main(String[] args) {
// HTML 转义
String html = "<div>Hello World</div>";
String escapedHtml = HtmlUtils.htmlEscape(html);
System.out.println("转义后的HTML: " + escapedHtml); // &lt;div&gt;Hello World&lt;/div&gt;

// HTML unescape
String unescapedHtml = HtmlUtils.htmlUnescape(escapedHtml);
System.out.println("unescape后的HTML: " + unescapedHtml); // <div>Hello World</div>

// JavaScript 转义
String js = "alert('Hello World');";
String escapedJs = HtmlUtils.javaScriptEscape(js);
System.out.println("转义后的JavaScript: " + escapedJs); // alert('Hello World');
}
}

其他常用工具类

1. ClassUtils

应用场景:类的加载、检查、操作等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import org.springframework.util.ClassUtils;

public class ClassUtilsDemo {
public static void main(String[] args) {
// 加载类
try {
Class<?> clazz = ClassUtils.forName("java.lang.String", ClassUtils.getDefaultClassLoader());
System.out.println("加载的类: " + clazz.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

// 检查类是否存在
boolean exists = ClassUtils.isPresent("java.lang.String", ClassUtils.getDefaultClassLoader());
System.out.println("String类是否存在: " + exists); // true

// 获取类的包名
String packageName = ClassUtils.getPackageName(String.class);
System.out.println("String类的包名: " + packageName); // java.lang

// 获取简单类名
String simpleName = ClassUtils.getShortName(String.class);
System.out.println("String类的简单名称: " + simpleName); // String

// 检查类是否为内部类
boolean isInnerClass = ClassUtils.isInnerClass(ClassUtilsDemo.class);
System.out.println("是否为内部类: " + isInnerClass); // false
}
}

2. FileCopyUtils

应用场景:文件的复制、读取、写入等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import org.springframework.util.FileCopyUtils;
import java.io.*;

public class FileCopyUtilsDemo {
public static void main(String[] args) throws IOException {
// 复制文件
File source = new File("source.txt");
File dest = new File("dest.txt");
FileCopyUtils.copy(source, dest);
System.out.println("文件复制完成");

// 读取文件内容
byte[] bytes = FileCopyUtils.copyToByteArray(source);
String content = new String(bytes);
System.out.println("文件内容: " + content);

// 写入文件
String newContent = "Hello Spring Boot";
FileCopyUtils.copy(newContent.getBytes(), dest);
System.out.println("文件写入完成");

// 从输入流复制到输出流
try (InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream("copy.txt")) {
FileCopyUtils.copy(is, os);
System.out.println("流复制完成");
}
}
}

3. Base64Utils

应用场景:Base64 编码和解码

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import org.springframework.util.Base64Utils;

public class Base64UtilsDemo {
public static void main(String[] args) {
// 编码
String original = "Hello Spring Boot";
byte[] encodedBytes = Base64Utils.encode(original.getBytes());
String encodedString = new String(encodedBytes);
System.out.println("Base64编码结果: " + encodedString);

// 解码
byte[] decodedBytes = Base64Utils.decode(encodedBytes);
String decodedString = new String(decodedBytes);
System.out.println("Base64解码结果: " + decodedString);

// URL安全的编码
byte[] urlEncodedBytes = Base64Utils.encodeUrlSafe(original.getBytes());
String urlEncodedString = new String(urlEncodedBytes);
System.out.println("URL安全的Base64编码结果: " + urlEncodedString);

// URL安全的解码
byte[] urlDecodedBytes = Base64Utils.decodeUrlSafe(urlEncodedBytes);
String urlDecodedString = new String(urlDecodedBytes);
System.out.println("URL安全的Base64解码结果: " + urlDecodedString);
}
}

冷门但有用的工具类

1. DigestUtils

应用场景:消息摘要计算(MD5、SHA 等)

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.util.DigestUtils;

public class DigestUtilsDemo {
public static void main(String[] args) {
// 计算MD5摘要
String original = "Hello Spring Boot";
String md5 = DigestUtils.md5DigestAsHex(original.getBytes());
System.out.println("MD5摘要: " + md5);

// 计算SHA-256摘要
String sha256 = DigestUtils.sha256AsHex(original.getBytes());
System.out.println("SHA-256摘要: " + sha256);
}
}

2. SystemPropertyUtils

应用场景:系统属性的解析和替换

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.util.SystemPropertyUtils;

public class SystemPropertyUtilsDemo {
public static void main(String[] args) {
// 解析包含系统属性的字符串
String path = SystemPropertyUtils.resolvePlaceholders("${user.home}/springboot");
System.out.println("解析后的路径: " + path);

// 解析时忽略未定义的属性
String config = SystemPropertyUtils.resolvePlaceholders("${app.home:default}/config");
System.out.println("解析后的配置路径: " + config);
}
}

3. Assert

应用场景:断言检查,用于参数验证等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import org.springframework.util.Assert;

public class AssertDemo {
public void processUser(String userId, String name) {
// 断言userId不为空
Assert.notNull(userId, "用户ID不能为空");

// 断言name不为空字符串
Assert.hasText(name, "用户名不能为空");

// 断言userId长度大于0
Assert.isTrue(userId.length() > 0, "用户ID长度必须大于0");

// 断言name长度在合理范围内
Assert.isTrue(name.length() >= 2 && name.length() <= 20, "用户名长度必须在2-20之间");

System.out.println("处理用户: " + userId + ", " + name);
}

public static void main(String[] args) {
AssertDemo demo = new AssertDemo();
try {
demo.processUser("123", "张三");
} catch (IllegalArgumentException e) {
System.out.println("断言失败: " + e.getMessage());
}
}
}

4. RandomValueStringGenerator

应用场景:生成随机字符串,用于令牌、密码等

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.springframework.util.RandomValueStringGenerator;

public class RandomValueStringGeneratorDemo {
public static void main(String[] args) {
// 创建默认生成器(长度为32,使用字母和数字)
RandomValueStringGenerator generator = new RandomValueStringGenerator();
String random1 = generator.generate();
System.out.println("默认随机字符串: " + random1);
System.out.println("长度: " + random1.length()); // 32

// 创建指定长度的生成器
RandomValueStringGenerator generator2 = new RandomValueStringGenerator(16);
String random2 = generator2.generate();
System.out.println("16位随机字符串: " + random2);
System.out.println("长度: " + random2.length()); // 16

// 生成多个随机字符串
for (int i = 0; i < 3; i++) {
System.out.println("随机字符串" + (i+1) + ": " + generator.generate());
}
}
}

总结

Spring Boot 3 提供了丰富的内置工具类,这些工具类可以大大简化开发工作,提高代码质量和开发效率。本文介绍了一些常用且高效的工具类,包括:

  1. 字符串工具类StringUtilsObjectUtils
  2. 集合工具类CollectionUtilsArrayUtils
  3. 时间日期工具类DateTimeUtilsStopWatch
  4. 反射工具类ReflectionUtils
  5. Web 相关工具类WebUtilsUriComponentsBuilderHtmlUtils
  6. 其他工具类ClassUtilsFileCopyUtilsBase64Utils
  7. 冷门但有用的工具类DigestUtilsSystemPropertyUtilsAssertRandomValueStringGenerator

这些工具类涵盖了开发中的各个方面,从基本的字符串操作到复杂的 Web 开发,都能找到相应的工具类来简化操作。在实际开发中,我们应该充分利用这些工具类,避免重复造轮子,提高开发效率和代码质量。

当然,Spring Boot 中还有许多其他的工具类,本文只是介绍了其中的一部分。在使用这些工具类时,我们应该查阅官方文档,了解它们的详细用法和注意事项,以便更好地应用到实际项目中。