想获取更多高质量的Java技术文章?欢迎访问 Java技术小馆官网,持续更新优质内容,助力技术成长!
SpringBoot 内置的 20 个高效工具类
还在自己写工具类?你已经被SpringBoot抛弃了!很多人嘴上说“别重复造轮子”,结果还在项目里一遍遍写String工具、Bean拷贝、文件处理、反射操作……
SpringBoot 内置了 20个宝藏工具类,轻量级、性能强、低耦合,很多大厂架构师都在用,可你可能连名字都没听过!
有人说:“用这些就像开了外挂。”
也有人说:“太黑箱,宁愿自己写。”
你怎么看?
一、数据处理
1. StringUtils
Spring 提供的 StringUtils
相比 Apache Commons Lang 版本更加轻量,且与 Spring 生态完美集成。它提供了字符串判空、截取、拼接等常用操作,比如:
// 判断字符串是否为空
StringUtils.isEmpty(str);
// 判断字符串是否有内容
StringUtils.hasText(str);
// 数组合并成字符串
StringUtils.arrayToCommaDelimitedString(arr);
2. ObjectUtils
处理对象判空和默认值时,不要再写 if-else 了:
// 安全判空
ObjectUtils.isEmpty(obj);
// 获取第一个非空对象
ObjectUtils.firstNonNull(obj1, obj2, defaultValue);
// 空安全toString
ObjectUtils.nullSafeToString(obj);
3. CollectionUtils
Spring 的集合工具类让集合操作更加优雅:
// 集合判空
CollectionUtils.isEmpty(collection);
// 查找第一个匹配元素
CollectionUtils.find(collection, predicate);
// 合并数组
CollectionUtils.mergeArrayIntoCollection(arr, collection);
二、HTTP 请求
1. RestTemplate
传统同步请求
虽然已被标记为过时,但在非响应式项目中依然实用:
// 简单GET请求
String result = restTemplate.getForObject(url, String.class);
// 带参数的POST请求
ResponseEntity<String> response = restTemplate.postForEntity(
url, request, String.class);
2. WebClient
Spring 5 引入的响应式 HTTP 客户端:
WebClient.create()
.get()
.uri(url)
.retrieve()
.bodyToMono(String.class)
.subscribe(result -> System.out.println(result));
3. TestTemplate
专门为测试设计的增强版 RestTemplate:
@Test
public void testApi() {
ResponseEntity<String> response = testRestTemplate
.getForEntity("/api/test", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
4. MockRestServiceServer
测试时模拟外部 API 调用:
MockRestServiceServer server = MockRestServiceServer
.bindTo(restTemplate).build();
server.expect(requestTo("/external/api"))
.andRespond(withSuccess("mock response", MediaType.APPLICATION_JSON));
三、缓存 & 异步
1. CacheManager
Spring 的缓存抽象层支持多种实现:
@Cacheable(value = "users", key = "#id")
public User getUser(Long id) {
// 数据库查询
}
@CacheEvict(value = "users", key = "#id")
public void updateUser(User user) {
// 更新逻辑
}
2. @Async
+ TaskExecutor
轻松实现方法异步执行:
@Async
public CompletableFuture<User> asyncGetUser(Long id) {
// 耗时操作
return CompletableFuture.completedFuture(user);
}
// 配置线程池
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
return executor;
}
3. EventPublishe
实现应用内事件发布订阅:
// 定义事件
public class UserRegisteredEvent extends ApplicationEvent {
public UserRegisteredEvent(User user) {
super(user);
}
}
// 发布事件
applicationEventPublisher.publishEvent(new UserRegisteredEvent(user));
// 监听事件
@EventListener
public void handleEvent(UserRegisteredEvent event) {
// 处理逻辑
}
四、校验 & 日志
1. Assert
Spring 的断言工具让参数检查更简洁:
// 参数校验
Assert.notNull(param, "参数不能为空");
Assert.isTrue(value > 0, "值必须大于0");
// 状态检查
Assert.state(isValid, "状态不合法");
2. @Validated
+ BindingResult
结合 JSR-303 实现参数校验:
@PostMapping("/users")
public ResponseEntity createUser(
@Validated @RequestBody User user,
BindingResult result) {
if (result.hasErrors()) {
// 处理校验错误
}
// 业务逻辑
}
3. Logback
/Log4j2
SpringBoot 自动配置的日志系统:
# application.properties
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
五、测试 & 调试
1. MockMvc
测试 Controller 层的利器:
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("张三"));
}
}
2. OutputCapture
捕获并验证日志输出:
@SpringBootTest
class LoggingTest {
@Autowired
private MyService service;
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
void testLogging() {
service.doSomething();
assertThat(outputCapture.toString())
.contains("操作已完成");
}
}
3. TestPropertyValues
灵活修改测试环境配置:
@Test
void testWithDynamicProperties() {
TestPropertyValues.of(
"app.timeout=5000",
"app.enabled=true"
).applyTo(environment);
// 执行测试
}
4. SpringBootTest
完整的集成测试支持:
@SpringBootTest(
webEnvironment = WebEnvironment.RANDOM_PORT,
properties = {"app.env=test"}
)
class FullIntegrationTest {
@LocalServerPort
private int port;
@Test
void testFullStack() {
// 测试完整应用栈
}
}
六、冷门但实用的工具
1. BannerCustomizer
让应用启动更有个性:
@Bean
public BannerCustomizer myBannerCustomizer() {
return banner -> {
banner.setBanner(new ResourceBanner(
new ClassPathResource("banner.txt")));
banner.setMode(Banner.Mode.LOG);
};
}
2. Environment
灵活访问环境变量和配置:
@Autowired
private Environment env;
public void someMethod() {
String dbUrl = env.getProperty("spring.datasource.url");
boolean debug = env.getProperty("app.debug", Boolean.class, false);
}
3. SpelExpressionParser
运行时执行 SpEL 表达式:
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name.toUpperCase()");
String result = exp.getValue(userContext, String.class);