为什么像 spring-security 这样的 spring boot 库在 /src/main 中有断言,而不是针对此类验证抛出异常?

Bip*_*sia 1 java spring spring-mvc spring-security spring-boot

在浏览 Spring Boot 存储库中的许多模块时,我可以在文件/src/main/中找到如下断言,

public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
            Set<String> scopes) {
        super(tokenValue, issuedAt, expiresAt);
        Assert.notNull(tokenType, "tokenType cannot be null");
        this.tokenType = tokenType;
        this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet());
    }
Run Code Online (Sandbox Code Playgroud)

难道不应该使用抛出异常来代替/src/main/.

据我所知,断言旨在与/src/test/.

chr*_*ke- 6

确实会引发异常。“断言”一词只是意味着“声明某件事应该是真的”,这可能发生在测试或运行时。您将一般断言的概念与assertJava 中关键字的特定工具或 AssertJ 等测试断言库合并。

在这种特殊情况下,Assert有问题的是org.springframework.util.Assert

/**
 * Assert that an object is not {@code null}.
 * <pre class="code">Assert.notNull(clazz, "The class must not be null");</pre>
 * @param object the object to check
 * @param message the exception message to use if the assertion fails
 * @throws IllegalArgumentException if the object is {@code null}
 */
public static void notNull(@Nullable Object object, String message) {
    if (object == null) {
        throw new IllegalArgumentException(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

PreconditionsGuava和 commons-lang也提供类似的功能Validate;它们不被称为“断言”,但它们具有相同的语义。