[英]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 等测试断言库合并。
在这种特殊情况下,有问题的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);
}
}
Guava Preconditions
和 commons-lang Validate
提供了类似的工具; 它们不被称为“断言”,但它们具有相同的语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.