Spring Boot 提供了许多内置工具类,这些类大多继承自 Spring Framework,旨在简化常见开发任务(如配置处理、资源加载、Bean 操作等)。以下是常用的工具类及其典型应用场景:
1. 应用启动与配置工具
-
SpringApplication
用于启动 Spring Boot 应用的核心类,支持自定义 Banner、配置文件、监听器等。
示例:
SpringApplication.run(MyApp.class, args);
-
SpringApplicationBuilder
链式 API 构建应用,支持多环境配置、父子上下文等。
示例:
javanew SpringApplicationBuilder(MyApp.class) .profiles("dev") .run(args);
-
ApplicationArguments
解析命令行参数,区分
--key=value
格式和非选项参数。示例:
java@Autowired private ApplicationArguments args; List<String> nonOptionArgs = args.getNonOptionArgs();
2. 环境配置与属性读取
-
Environment
获取应用配置(如
application.properties
中的属性、系统变量等)。示例:
java@Autowired private Environment env; String port = env.getProperty("server.port");
-
@ConfigurationProperties
将配置属性绑定到 Java 对象,支持类型安全访问。
示例:
java@ConfigurationProperties(prefix = "myapp") public class MyConfig { private String name; // getter/setter }
3. Bean 操作工具
-
ApplicationContextAware
获取 Spring 上下文,动态获取 Bean。
示例:
java@Component public class MyBean implements ApplicationContextAware { private ApplicationContext context; @Override public void setApplicationContext(ApplicationContext context) { this.context = context; } public Object getBean(String name) { return context.getBean(name); } }
-
BeanUtils
复制 Bean 属性、实例化对象等。
示例:
javaMyBean dest = new MyBean(); BeanUtils.copyProperties(source, dest); // 同名属性复制
-
ObjectProvider
延迟注入 Bean,避免依赖不存在时的异常。
示例:
java@Autowired private ObjectProvider<MyService> myServiceProvider; MyService service = myServiceProvider.getIfAvailable();
4. 资源处理工具
-
ResourceUtils
获取类路径、文件系统中的资源。
示例:
javaFile file = ResourceUtils.getFile("classpath:config/file.txt");
-
FileCopyUtils
简化文件复制和内容读写。
示例:
javabyte[] data = FileCopyUtils.copyToByteArray(new FileInputStream("test.txt"));
5. 断言与校验工具
-
Assert
快速校验参数合法性,抛出
IllegalArgumentException
或IllegalStateException
。示例:
javaAssert.notNull(obj, "对象不能为空"); Assert.hasText(str, "字符串必须非空");
-
ValidationUtils
结合 Spring Validator 进行数据校验。
示例:
javaValidationUtils.rejectIfEmpty(errors, "name", "name.empty");
6. 集合与对象工具
-
CollectionUtils
集合判空、合并、过滤等操作。
示例:
javaif (CollectionUtils.isEmpty(list)) { ... }
-
ObjectUtils
对象判空、默认值处理。
示例:
javaString value = ObjectUtils.defaultIfNull(str, "default");
7. SpEL 表达式工具
-
SpelExpressionParser
解析 SpEL 表达式,动态求值。
示例:javaExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("'Hello ' + name"); String result = exp.getValue(context, String.class);
8. AOP 工具
-
AopUtils
判断代理类型、获取目标类等。
示例:javaif (AopUtils.isAopProxy(bean)) { ... }
9. 事件与监听
-
ApplicationEventPublisher
发布自定义事件。
示例:java@Autowired private ApplicationEventPublisher publisher; publisher.publishEvent(new MyEvent("事件内容"));
10. Web 相关工具
-
ResponseEntity
封装 HTTP 响应,包括状态码、头信息、响应体。
示例:
javareturn ResponseEntity.status(HttpStatus.OK).body("Success");
-
ServletUtils
处理请求与响应(如获取请求参数)。
示例:
javaHttpServletRequest request = ServletUtils.getRequest();
11. 测试工具
-
TestPropertySource
为测试类指定配置文件。
示例:
java@TestPropertySource(locations = "classpath:test.properties")
-
MockMvc
模拟 HTTP 请求,测试 Controller 层。
示例:
javamockMvc.perform(get("/api/data")) .andExpect(status().isOk());
12. 其他工具
-
StringUtils
字符串判空、截断、分割等(
org.springframework.util
包)。示例:
javaif (StringUtils.hasText(str)) { ... }
-
JsonUtils
(需配合 Jackson)JSON 序列化与反序列化。
示例:
javaString json = JsonUtils.toJson(obj); MyObject obj = JsonUtils.fromJson(json, MyObject.class);