Spring Boot 凭借其强大的自动配置和丰富的生态系统,已成为首选的 Java 开发框架。除了核心功能,Spring 框架本身还封装了大量鲜为人知但又极其有用的工具类 (Utility Classes)。熟练掌握这些内置工具,可以帮助你编写出更简洁、健壮的代码,并有效减少对 Apache Commons 或 Guava 等外部库的依赖,让你无需“重复造轮子”。
本文将为你详细梳理这 49 个不可或缺的实用工具类,并附上简洁明了的代码示例,助你快速上手,提升日常开发效率。
字符串处理
1. StringUtils
一个功能全面的字符串操作工具,尤其擅长处理空值检查和空白字符。
import org.springframework.util.StringUtils;
// 检查字符串是否为空或 null
boolean isEmpty1 = StringUtils.isEmpty(null); // true
boolean isEmpty2 = StringUtils.isEmpty(""); // true
// 检查字符串是否有实际文本内容(不仅仅是空格)
boolean hasText1 = StringUtils.hasText(" "); // false
boolean hasText2 = StringUtils.hasText("hello"); // true
// 将字符串标记化为数组
String[] parts = StringUtils.tokenizeToStringArray("a,b,c", ","); // ["a", "b", "c"]
// 去除开头和结尾的空格
String trimmed = StringUtils.trimWhitespace(" hello "); // "hello"
2. AntPathMatcher
一个强大的路径模式匹配工具,采用 Ant 风格,常用于 URL 路由和权限配置等场景。
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*"}, "adminuser"); // true
4. PropertyPlaceholderHelper
用于解析字符串中形如 ${name} 的占位符,并能够根据给定的属性源进行替换。
import org.springframework.util.PropertyPlaceholderHelper;
import java.util.Properties;
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");
Properties props = new Properties();
props.setProperty("name", "World");
props.setProperty("greeting", "Hello ${name}!");
String result = helper.replacePlaceholders("${greeting}", props::getProperty);
// result -> "Hello World!"
集合与数组处理
5. CollectionUtils
提供广泛的集合操作工具,例如空值检查以及执行集合交、并、差等运算。
import org.springframework.util.CollectionUtils;
import java.util.*;
// 检查集合是否为 null 或空
boolean isEmpty1 = 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]
6. MultiValueMap
标准 Map 接口的一个扩展,允许为单个键存储多个值,在处理 HTTP 请求头等场景时非常有用。
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
一个线程安全的、基于软/弱引用的 Map 实现,非常适合缓存场景。当内存不足时,垃圾收集器可以自动回收其中的条目。
import org.springframework.util.ConcurrentReferenceHashMap;
import java.util.Map;
// 为高并发缓存创建一个线程安全的 map
Map<String, Object> cache = new ConcurrentReferenceHashMap<>();
cache.put("key1", new Object()); // 如果内存不足,该值可以被垃圾回收
8. SystemPropertyUtils
专门用于解析 JVM 系统属性中的占位符,方便获取运行时环境信息。
import org.springframework.util.SystemPropertyUtils;
// 使用系统属性解析占位符
String javaHome = SystemPropertyUtils.resolvePlaceholders("${java.home}");
// 如果找不到属性,则提供默认值
String pathWithDefault = SystemPropertyUtils.resolvePlaceholders(
"${unknown.property:default_value}"); // "default_value"
反射与类操作
9. ReflectionUtils
提供一组用于处理低级反射任务的静态方法,例如查找字段、调用私有方法等,并且能够优雅地处理访问权限和异常。
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
// 查找并设置字段值
Field field = ReflectionUtils.findField(MyClass.class, "name");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, myObject, "John");
// 查找并调用方法
Method method = ReflectionUtils.findMethod(MyClass.class, "setAge", int.class);
ReflectionUtils.invokeMethod(method, myObject, 30);
10. ClassUtils
提供了处理 Class 对象的多种实用工具,例如获取短类名、判断类是否存在等。
import org.springframework.util.ClassUtils;
// 获取类的短名称
String shortName = ClassUtils.getShortName("org.example.MyClass"); // "MyClass"
// 检查类路径上是否存在某个类
boolean exists = ClassUtils.isPresent("java.util.List", null); // true
// 获取默认的类加载器
ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
11. MethodInvoker
提供了一种便捷的方式来准备和调用目标对象上的方法,支持参数传递。
import org.springframework.util.MethodInvoker;
MethodInvoker invoker = new MethodInvoker();
invoker.setTargetObject(new MyService());
invoker.setTargetMethod("calculateTotal");
invoker.setArguments(100, 0.2);
invoker.prepare();
Object result = invoker.invoke();
12. BeanUtils
一个强大的工具,用于常见的 Bean 操作,例如在不同对象间复制同名属性,或者使用默认构造函数实例化类。
import org.springframework.beans.BeanUtils;
// 将属性从源对象复制到目标对象
Person source = new Person("John", 30);
PersonDTO target = new PersonDTO();
BeanUtils.copyProperties(source, target);
// 使用默认构造函数实例化一个类
Person newPerson = BeanUtils.instantiateClass(Person.class);
I/O 操作
13. FileCopyUtils
提供了一系列简单的静态方法,用于在文件、流、Reader 和 Writer 之间高效地复制数据。
import org.springframework.util.FileCopyUtils;
import java.io.*;
// 将文件内容复制到字节数组
byte[] bytes = FileCopyUtils.copyToByteArray(new File("input.txt"));
FileCopyUtils.copy(bytes, new File("output.txt"));
// 将内容从 Reader 复制到 String
String content = FileCopyUtils.copyToString(new FileReader("input.txt"));
// 在流之间复制
FileCopyUtils.copy(new FileInputStream("input.txt"), new FileOutputStream("output.txt"));
14. ResourceUtils
用于将带有特定前缀(如 classpath: 或 file:)的资源位置字符串解析为 File 或 URL 对象。
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.net.URL;
// 从类路径获取文件
File file = ResourceUtils.getFile("classpath:config.properties");
// 检查字符串是否为 URL
boolean isUrl = ResourceUtils.isUrl("http://example.com"); // true
// 从位置字符串获取 URL
URL url = ResourceUtils.getURL("classpath:data.json");
15. StreamUtils
包含处理 InputStream 和 OutputStream 的实用方法,能有效减少处理 I/O 流时的样板代码。
import org.springframework.util.StreamUtils;
import java.nio.charset.StandardCharsets;
// 将流复制到字节数组
byte[] data = StreamUtils.copyToByteArray(inputStream);
// 将流复制到字符串
String text = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
// 将字符串复制到输出流
StreamUtils.copy("Hello", StandardCharsets.UTF_8, outputStream);
16. FileSystemUtils
提供文件系统操作工具,其中最突出的是递归复制和删除整个目录。
import org.springframework.util.FileSystemUtils;
import java.io.File;
// 递归删除目录及其内容
boolean deleted = FileSystemUtils.deleteRecursively(new File("/tmp/test"));
// 递归复制目录及其内容
FileSystemUtils.copyRecursively(new File("source"), new File("target"));
17. ResourcePatternUtils
用于将资源模式(如 classpath*:**/*.xml)解析为 Resource 对象数组,便于批量加载类路径资源。
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
// 在所有类路径位置的 META-INF 目录中查找所有 XML 文件
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:META-INF/*.xml");
Web 相关
18. WebUtils
一个 Web 实用程序的集合,简化了从 HttpServletRequest 中获取 Cookie、参数等常见任务。
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Cookie;
// 从请求中获取特定的 cookie
Cookie cookie = WebUtils.getCookie(request, "sessionId");
// 获取带有默认值的请求参数
int pageSize = WebUtils.getIntParameter(request, "pageSize", 10);
19. UriUtils
根据 RFC 3986 标准对 URI 的各个组件(如路径、查询参数)进行编码和解码的辅助工具。
import org.springframework.web.util.UriUtils;
import java.nio.charset.StandardCharsets;
// 编码 URI 路径段
String encoded = UriUtils.encodePathSegment("path with spaces", StandardCharsets.UTF_8);
// 解码回原始段
String decoded = UriUtils.decode(encoded, StandardCharsets.UTF_8);
20. UriComponentsBuilder
一个可变的构建器,可以用于从头开始创建 UriComponents,也可以通过修改现有 URI 来构造新的 URI。
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
// 以流畅的方式构建复杂的 URI
URI uri = UriComponentsBuilder.fromHttpUrl("http://example.com")
.path("/products/{id}")
.queryParam("category", "books")
.build("123");
// 结果: http://example.com/products/123?category=books
21. ContentCachingRequestWrapper
一个 HttpServletRequest 的包装器,它缓存了请求体,使得请求负载可以被多次读取。
import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.servlet.http.HttpServletRequest;
// 包装请求,例如在过滤器中
ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
// ... 稍后,在处理完请求之后
byte[] body = wrapper.getContentAsByteArray();
String bodyAsString = new String(body, wrapper.getCharacterEncoding());
22. HtmlUtils
用于 HTML 转义和反转义的工具,是防止跨站脚本 (XSS) 攻击的第一道防线。
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
提供了一系列静态断言方法,用于检查方法参数或状态的前置条件。如果断言失败,它会抛出 IllegalArgumentException 或 IllegalStateException。
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 collection must not be empty");
Assert.state(isInitialized, "Service is not initialized");
24. ObjectUtils
专注于处理对象的工具,特别是进行空安全 (null-safe) 的操作和检查各种类型(如数组、集合)是否为空。
import org.springframework.util.ObjectUtils;
// 检查对象是否为空(null、空字符串、空数组或空集合)
boolean isEmpty1 = ObjectUtils.isEmpty(null); // true
boolean isEmpty2 = ObjectUtils.isEmpty(new int[0]); // true
// 空安全的 equals 比较
boolean equals = ObjectUtils.nullSafeEquals(obj1, obj2);
// 如果对象为 null,则获取默认值
String value = ObjectUtils.getOrDefault(null, "default"); // "default"
25. NumberUtils
提供了在不同数字类型之间进行转换以及将字符串解析为指定数字类型的方法。
import org.springframework.util.NumberUtils;
// 将字符串解析为特定的数字类型
Integer parsedInt = NumberUtils.parseNumber("42", Integer.class);
// 将一种数字类型转换为另一种
Double convertedDouble = NumberUtils.convertNumberToTargetClass(42, Double.class);
日期与时间
一个灵活的 java.util.Date 对象格式化程序,用于日期对象和字符串表示之间的相互转换。
import org.springframework.format.datetime.DateFormatter;
import java.util.Date;
import java.util.Locale;
// 注意:Spring 倾向于使用 formatters 而不是静态的 DateTimeUtils 类。
DateFormatter formatter = new DateFormatter("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.print(new Date(), Locale.getDefault());
27. StopWatch
一个简单的任务计时工具,提供了便捷的方式来测量不同代码块或任务阶段的执行时间。
import org.springframework.util.StopWatch;
// 一个简单的性能计时工具
StopWatch watch = new StopWatch("MyTask");
watch.start("Phase 1: Data Loading");
// ... 执行数据加载任务
Thread.sleep(100);
watch.stop();
watch.start("Phase 2: Data Processing");
// ... 执行处理任务
Thread.sleep(200);
watch.stop();
// 打印格式化的计时摘要
System.out.println(watch.prettyPrint());
安全相关
28. DigestUtils
提供创建消息摘要(哈希值,如 MD5、SHA)的静态方法,常用于密码摘要或文件完整性校验。
import org.springframework.util.DigestUtils;
import java.io.InputStream;
import java.io.FileInputStream;
// 创建字符串的 MD5 哈希
String md5Hex = DigestUtils.md5DigestAsHex("password".getBytes());
// 创建文件内容的 MD5 哈希
try (InputStream is = new FileInputStream("file.txt")) {
String fileMd5 = DigestUtils.md5DigestAsHex(is);
}
29. Base64Utils
用于 Base64 编码和解码数据的工具类,简化了处理 Base64 字符串的操作。
import org.springframework.util.Base64Utils;
byte[] data = "Hello World".getBytes();
// 将数据编码为 Base64 字符串
String encoded = Base64Utils.encodeToString(data);
// 将 Base64 字符串解码回数据
byte[] decoded = Base64Utils.decodeFromString(encoded);
30. TextEncryptor
Spring Security 提供的接口,用于文本的双向加密和解密,为敏感信息提供了一层保护。
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
// 注意:需要 spring-security-crypto 依赖
String password = "my-secret-password";
String salt = "deadbeef"; // hex-encoded
TextEncryptor encryptor = Encryptors.text(password, salt);
String encryptedText = encryptor.encrypt("This is a secret message");
String decryptedText = encryptor.decrypt(encryptedText);
JSON 与数据转换
31. JsonParserFactory
用于获取 JsonParser 实例的工厂,提供了一种轻量级的方法来解析 JSON 字符串,而无需引入完整的数据绑定库(如 Jackson ObjectMapper)。
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import java.util.Map;
import java.util.List;
// 获取默认的 JSON 解析器
JsonParser parser = JsonParserFactory.getJsonParser();
// 将 JSON 对象解析为 Map
Map<String, Object> map = parser.parseMap("{\"name\":\"John\", \"age\":30}");
// 将 JSON 数组解析为 List
List<Object> list = parser.parseList("[1, 2, 3]");
32. ResolvableType
提供了一种在运行时处理复杂泛型类型的机制,解决了普通 java.lang.Class 在泛型信息擦除后的局限性。
import org.springframework.core.ResolvableType;
import java.util.List;
import java.util.Map;
// 获取集合的泛型类型
ResolvableType listType = ResolvableType.forField(getClass().getDeclaredField("myList"));
ResolvableType elementType = listType.getGeneric(0); // 例如,对于 List<String> 是 String
// 为泛型类创建可解析类型
ResolvableType mapType = ResolvableType.forClassWithGenerics(Map.class, String.class, Integer.class);
33. MappingJackson2HttpMessageConverter
Spring MVC 中用于在 Java 对象和 JSON 之间进行序列化与反序列化的核心组件,可以进行高度自定义以满足特定需求。
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
// 创建并自定义 JSON 消息转换器
ObjectMapper customMapper = new ObjectMapper();
// ... 配置 ObjectMapper 属性(例如,日期格式、特性)
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(customMapper);
其他实用工具
34. RandomStringUtils (Apache Commons)
虽然不是 Spring 原生类,但在 Spring Boot 项目中经常通过 spring-boot-starter 间接引入。它用于生成各种类型的随机字符串,非常方便。
// 注意:来自 org.apache.commons.lang3 库
import org.apache.commons.lang3.RandomStringUtils;
// 生成随机字符串
String randomAlpha = RandomStringUtils.randomAlphabetic(10);
String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(10);
String randomNumeric = RandomStringUtils.randomNumeric(6);
35. CompletableFuture
标准 Java 类,但在构建现代异步 Spring 应用程序时必不可少。利用其静态方法可以优雅地组合多个异步操作的结果。
import java.util.concurrent.CompletableFuture;
import java.util.List;
import java.util.stream.Collectors;
// 组合多个异步结果的常见模式
List<CompletableFuture<String>> futures = /* 异步调用的 future 列表 */;
CompletableFuture<Void> allOf = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0]));
CompletableFuture<List<String>> allResults = allOf.thenApply(v ->
futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
36. CacheControl
一个构建器类,用于以类型安全的方式创建 HTTP Cache-Control 响应头的值。
import org.springframework.http.CacheControl;
import java.util.concurrent.TimeUnit;
// 构建 Cache-Control 标头值
CacheControl cacheControl = CacheControl.maxAge(1, TimeUnit.HOURS)
.noTransform()
.mustRevalidate();
String headerValue = cacheControl.getHeaderValue(); // "max-age=3600, no-transform, must-revalidate"
37. AnnotationUtils
一个强大的工具,用于在类、方法和字段上查找注解。它支持元注解和合并注解属性,比 Java 原生的反射 API 更加强大和易用。
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
// 查找类上的注解,向上搜索层次结构
Component annotation = AnnotationUtils.findAnnotation(MyService.class, Component.class);
// 从注解中获取特定的属性值
String value = (String) AnnotationUtils.getValue(annotation, "value");
38. DefaultConversionService
Spring 对 ConversionService 接口的默认实现。它注册了许多转换器,可以在标准类型(例如字符串到整数、字符串到布尔值)之间进行转换。
import org.springframework.core.convert.support.DefaultConversionService;
// 创建转换服务实例
DefaultConversionService conversionService = new DefaultConversionService();
// 将字符串转换为整数
Integer intValue = conversionService.convert("42", Integer.class);
Boolean boolValue = conversionService.convert("true", Boolean.class);
一个专门用于处理 HTTP 标头的 MultiValueMap 实现。它提供了许多便捷的常量(如 Content-Type)和方法来简化标头的构建。
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
// 构建 HTTP 标头的便捷方式
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setContentLength(1024);
headers.setCacheControl("max-age=3600");
提供了一种根据文件扩展名或文件名来确定资源对应 MediaType(MIME 类型)的方法。
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import java.util.Optional;
// 根据文件名猜测媒体类型
Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("document.pdf");
// 返回 Optional[application/pdf]
41. MimeTypeUtils
包含常见 MIME 类型的常量,并提供了一些处理 MIME 类型的实用方法,例如判断两个 MIME 类型是否兼容。
import org.springframework.util.MimeTypeUtils;
// 提供常见的 MIME 类型常量和实用程序
MimeType a = MimeTypeUtils.APPLICATION_JSON;
MimeType b = MimeType.valueOf("application/*");
boolean isCompatible = a.isCompatibleWith(b); // true
42. WebClient.Builder
创建 WebClient(Spring 5 引入的现代非阻塞反应式 HTTP 客户端)实例的主要工具。通过构建器模式可以灵活配置客户端。
import org.springframework.web.reactive.function.client.WebClient;
// 使用构建器来配置和创建 WebClient 实例
WebClient webClient = WebClient.builder()
.baseUrl("https://api.example.com")
.defaultHeader("Authorization", "Bearer my-token")
.build();
43. PropertySourceUtils
一个辅助工具,用于处理 Spring 环境(Environment)中所包含的 PropertySource 对象中的属性值。
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
// 将属性源添加到环境的示例
Map<String, Object> myProps = new HashMap<>();
myProps.put("app.name", "MyApp");
PropertySource<?> myPropertySource = new MapPropertySource("my-properties", myProps);
environment.getPropertySources().addFirst(myPropertySource);
44. ApplicationEventPublisher
Spring 应用程序上下文的核心接口,用于发布应用程序事件。这是实现解耦的事件驱动架构的基础。
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
private ApplicationEventPublisher eventPublisher;
public void doSomething() {
// ... 逻辑 ...
MyCustomEvent event = new MyCustomEvent(this, "Something important happened");
eventPublisher.publishEvent(event);
}
45. LocaleContextHolder
一个用于持有当前线程的 Locale(区域设置)的持有器。对于实现国际化 (i18n) 和多语言支持至关重要。
import org.springframework.context.i18n.LocaleContextHolder;
import java.util.Locale;
// 获取当前请求/线程的 locale
Locale currentLocale = LocaleContextHolder.getLocale();
// 以编程方式设置 locale
LocaleContextHolder.setLocale(Locale.FRENCH);
46. AopUtils
一组用于处理 Spring AOP 代理的静态实用方法。可以用来判断一个对象是否为代理、获取代理背后的目标类等。
import org.springframework.aop.support.AopUtils;
// 检查对象是否为 Spring AOP 代理
boolean isAopProxy = AopUtils.isAopProxy(myBean);
// 检查是否为基于 CGLIB 的代理
boolean isCglibProxy = AopUtils.isCglibProxy(myBean);
// 获取代理的底层目标类
Class<?> targetClass = AopUtils.getTargetClass(myBean);
47. ProxyFactory
一种以编程方式创建 AOP 代理的方法。它允许你精细地控制为目标对象应用哪些接口和通知(Advice)。
import org.springframework.aop.framework.ProxyFactory;
// 以编程方式为目标对象创建代理
ProxyFactory factory = new ProxyFactory(myTargetObject);
factory.addAdvice(new MyMethodInterceptor()); // 添加建议 (Advice)
MyInterface proxy = (MyInterface) factory.getProxy();
48. ClassPathScanningCandidateComponentProvider
一个强大的工具,用于扫描类路径以查找符合特定条件(通常由过滤器定义)的组件(即候选的 Bean 定义)。
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.beans.factory.config.BeanDefinition;
import java.util.Set;
// 扫描类路径以查找带有 @Component 注解的类
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(true);
scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));
Set<BeanDefinition> components = scanner.findCandidateComponents("com.example.myapp");
49. YamlPropertiesFactoryBean
一个工厂 Bean,可以加载 YAML 格式的配置文件,并将其内容转换为标准的 Properties 对象,便于在传统属性 API 中使用。
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import java.util.Properties;
// 加载 YAML 文件并将其视为 Properties 对象
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ClassPathResource("application.yml"));
Properties properties = yamlFactory.getObject();
String appName = properties.getProperty("spring.application.name");
总结
以上这些实用程序类覆盖了 Java 开发中从字符串处理、集合操作、反射、I/O 到安全、Web 交互等众多常见场景。它们是 Spring 生态中沉淀下来的精华,熟练掌握并运用它们,可以显著提升你的开发效率,减少样板代码,并帮助你编写出更清晰、更符合 Spring 风格的应用程序。
如果你想深入探讨某个工具类的使用技巧,或者分享你在实际项目中应用这些工具类的经验,欢迎来 云栈社区 与广大开发者一起交流学习。