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)); System.out.println("str2 是否为空: " + StringUtils.isEmpty(str2)); System.out.println("str3 是否为空: " + StringUtils.isEmpty(str3)); System.out.println("str3 是否为空白: " + StringUtils.isBlank(str3)); String str4 = " Hello World "; System.out.println("修剪后: " + StringUtils.trimWhitespace(str4)); String str5 = "a,b,c,d"; String[] parts = StringUtils.split(str5, ","); System.out.println("分割结果: " + Arrays.toString(parts)); String str6 = "Hello {name}"; String replaced = StringUtils.replace(str6, "{name}", "Spring Boot"); System.out.println("替换结果: " + replaced); String str7 = "SpringBootApplication"; System.out.println("是否以Spring开头: " + StringUtils.startsWith(str7, "Spring")); System.out.println("是否以Application结尾: " + StringUtils.endsWith(str7, "Application")); } }
|
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)); System.out.println("obj2 是否为空: " + ObjectUtils.isEmpty(obj2)); Integer num1 = 10; Integer num2 = 10; Integer num3 = 20; System.out.println("num1 和 num2 是否相等: " + ObjectUtils.nullSafeEquals(num1, num2)); System.out.println("num1 和 num3 是否相等: " + ObjectUtils.nullSafeEquals(num1, num3)); Object obj3 = 123; Object obj4 = null; System.out.println("obj3 转换为字符串: " + ObjectUtils.nullSafeToString(obj3)); System.out.println("obj4 转换为字符串: " + ObjectUtils.nullSafeToString(obj4)); System.out.println("obj2 的类名: " + ObjectUtils.getClassName(obj2)); System.out.println("obj4 的类名: " + ObjectUtils.getClassName(obj4)); } }
|
集合工具类
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)); System.out.println("list2 是否为空: " + CollectionUtils.isEmpty(list2)); System.out.println("list3 是否为空: " + CollectionUtils.isEmpty(list3)); List<String> list4 = List.of("d", "e", "f"); List<String> mergedList = new ArrayList<>(list3); CollectionUtils.mergeArrayIntoCollection(list4.toArray(), mergedList); System.out.println("合并后的集合: " + mergedList); System.out.println("list3 是否包含a: " + CollectionUtils.contains(list3.iterator(), "a")); 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)); System.out.println("map2 是否为空: " + CollectionUtils.isEmpty(map2)); System.out.println("map3 是否为空: " + CollectionUtils.isEmpty(map3)); } }
|
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)); System.out.println("arr2 是否为空: " + ArrayUtils.isEmpty(arr2)); System.out.println("arr3 是否为空: " + ArrayUtils.isEmpty(arr3)); String[] arr4 = {"d", "e", "f"}; String[] mergedArray = ArrayUtils.addAll(arr3, arr4); System.out.println("合并后的数组: " + Arrays.toString(mergedArray)); int index = ArrayUtils.indexOf(arr3, "b"); System.out.println("b 的索引: " + index); System.out.println("arr3 是否包含c: " + ArrayUtils.contains(arr3, "c")); List<String> list = Arrays.asList(arr3); System.out.println("数组转列表: " + list); } }
|
时间日期工具类
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); long timestamp = System.currentTimeMillis(); Date dateFromTimestamp = new Date(timestamp); System.out.println("时间戳转日期: " + DateTimeUtils.formatDateTime(dateFromTimestamp)); LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedNow = now.format(formatter); System.out.println("LocalDateTime 格式化: " + formattedNow); 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("测试代码执行时间"); stopWatch.start("任务1"); Thread.sleep(1000); stopWatch.stop(); System.out.println("任务1 执行时间: " + stopWatch.getLastTaskTimeMillis() + "ms"); stopWatch.start("任务2"); Thread.sleep(1500); stopWatch.stop(); System.out.println("任务2 执行时间: " + stopWatch.getLastTaskTimeMillis() + "ms"); 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); boolean isAjax = WebUtils.isAjaxRequest(request); System.out.println("是否为ajax请求: " + isAjax); 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) { 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); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/api/users?id=123&name=test"); System.out.println("主机: " + builder.build().getHost()); System.out.println("路径: " + builder.build().getPath()); System.out.println("查询参数: " + builder.build().getQuery()); } }
|
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) { String html = "<div>Hello World</div>"; String escapedHtml = HtmlUtils.htmlEscape(html); System.out.println("转义后的HTML: " + escapedHtml); String unescapedHtml = HtmlUtils.htmlUnescape(escapedHtml); System.out.println("unescape后的HTML: " + unescapedHtml); String js = "alert('Hello World');"; String escapedJs = HtmlUtils.javaScriptEscape(js); System.out.println("转义后的JavaScript: " + escapedJs); } }
|
其他常用工具类
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); String packageName = ClassUtils.getPackageName(String.class); System.out.println("String类的包名: " + packageName); String simpleName = ClassUtils.getShortName(String.class); System.out.println("String类的简单名称: " + simpleName); boolean isInnerClass = ClassUtils.isInnerClass(ClassUtilsDemo.class); System.out.println("是否为内部类: " + isInnerClass); } }
|
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); byte[] urlEncodedBytes = Base64Utils.encodeUrlSafe(original.getBytes()); String urlEncodedString = new String(urlEncodedBytes); System.out.println("URL安全的Base64编码结果: " + urlEncodedString); 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) { String original = "Hello Spring Boot"; String md5 = DigestUtils.md5DigestAsHex(original.getBytes()); System.out.println("MD5摘要: " + md5); 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) { Assert.notNull(userId, "用户ID不能为空"); Assert.hasText(name, "用户名不能为空"); Assert.isTrue(userId.length() > 0, "用户ID长度必须大于0"); 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) { RandomValueStringGenerator generator = new RandomValueStringGenerator(); String random1 = generator.generate(); System.out.println("默认随机字符串: " + random1); System.out.println("长度: " + random1.length()); RandomValueStringGenerator generator2 = new RandomValueStringGenerator(16); String random2 = generator2.generate(); System.out.println("16位随机字符串: " + random2); System.out.println("长度: " + random2.length()); for (int i = 0; i < 3; i++) { System.out.println("随机字符串" + (i+1) + ": " + generator.generate()); } } }
|
总结
Spring Boot 3 提供了丰富的内置工具类,这些工具类可以大大简化开发工作,提高代码质量和开发效率。本文介绍了一些常用且高效的工具类,包括:
- 字符串工具类:
StringUtils、ObjectUtils
- 集合工具类:
CollectionUtils、ArrayUtils
- 时间日期工具类:
DateTimeUtils、StopWatch
- 反射工具类:
ReflectionUtils
- Web 相关工具类:
WebUtils、UriComponentsBuilder、HtmlUtils
- 其他工具类:
ClassUtils、FileCopyUtils、Base64Utils
- 冷门但有用的工具类:
DigestUtils、SystemPropertyUtils、Assert、RandomValueStringGenerator
这些工具类涵盖了开发中的各个方面,从基本的字符串操作到复杂的 Web 开发,都能找到相应的工具类来简化操作。在实际开发中,我们应该充分利用这些工具类,避免重复造轮子,提高开发效率和代码质量。
当然,Spring Boot 中还有许多其他的工具类,本文只是介绍了其中的一部分。在使用这些工具类时,我们应该查阅官方文档,了解它们的详细用法和注意事项,以便更好地应用到实际项目中。