繁体   English   中英

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

[英]Why does spring boot libraries like spring-security have assertions in /src/main and not exceptions thrown for such validations?

在从 spring 引导存储库中遍历许多模块时,我可以在/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());
    }

对于/src/main/下的所有此类验证,是否应该使用异常来代替。

据我所知,断言旨在与/src/test/下的测试用例一起使用。

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

在这种特殊情况下,有问题的Assertorg.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);
    }
}

Guava Preconditions和 commons-lang Validate提供了类似的工具; 它们不被称为“断言”,但它们具有相同的语义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM