断言工具 - Assert
概述
Assert 是 Spring Framework 提供的断言工具类,用于简化参数校验,减少样板代码。
核心能力矩阵
| 能力 | 核心类 | 解决的问题 | 使用频率 | 学习优先级 |
|---|---|---|---|---|
| 断言工具 | Assert | 参数校验样板代码 | ⭐⭐⭐⭐⭐ | 🔴 高 |
设计目标
- 简化参数校验代码
- 提供统一的异常抛出机制
- 支持常见的校验场景
核心方法
主要功能
1. 非空断言
java
// 断言对象不为 null
Assert.notNull(user, "User must not be null");
// 断言字符串有长度
Assert.hasLength(name, "Name must not be empty");
// 断言字符串有实际内容(不只是空白字符)
Assert.hasText(description, "Description must have text");2. 条件断言
java
// 断言表达式为 true
Assert.isTrue(age > 0, "Age must be positive");
// 断言状态(抛出 IllegalStateException)
Assert.state(isInitialized, "Service must be initialized");3. 集合/数组断言
java
// 断言集合不为空
Assert.notEmpty(items, "Items list must not be empty");
// 断言数组不为空
Assert.notEmpty(elements, "Elements array must not be empty");异常类型
| 断言方法 | 异常类型 |
|---|---|
notNull() | IllegalArgumentException |
hasLength() | IllegalArgumentException |
hasText() | IllegalArgumentException |
isTrue() | IllegalArgumentException |
notEmpty() | IllegalArgumentException |
state() | IllegalStateException |
使用场景
- 方法参数校验
- 前置条件检查
- 状态验证
- 防御性编程
最佳实践
java
public void createUser(String username, String email, Integer age) {
// 参数校验
Assert.hasText(username, "Username must not be empty");
Assert.hasText(email, "Email must not be empty");
Assert.notNull(age, "Age must not be null");
Assert.isTrue(age > 0, "Age must be positive");
// 业务逻辑
// ...
}