1. Overview
1.概述
In this tutorial, we’ll focus on and describe the purpose of the Spring Assert class and demonstrate how to use it.
在本教程中,我们将关注并描述Spring Assert类的目的,并演示如何使用它。
2. Purpose of the Assert Class
2、Assert类的目的
The Spring Assert class helps us validate arguments. By using methods of the Assert class, we can write assumptions which we expect to be true. And if they aren’t met, a runtime exception is thrown.
Spring的Assert类帮助我们验证参数。通过使用Assert类的方法,我们可以编写我们期望为真的假设。如果这些假设没有得到满足,就会抛出一个运行时异常。
Each Assert’s method can be compared with the Java assert statement. Java assert statement throws an Error at runtime if its condition fails. The interesting fact is that those assertions can be disabled.
每个Assert的方法都可以与Java assert语句进行比较。Java assert语句在运行时抛出一个Error,如果其条件失败。有趣的事实是,这些断言可以被禁用。
Here are some characteristics of the Spring Assert’s methods:
下面是Spring Assert方法的一些特点。
- Assert’s methods are static
- They throw either IllegalArgumentException or IllegalStateException
- The first parameter is usually an argument for validation or a logical condition to check
- The last parameter is usually an exception message which is displayed if the validation fails
- The message can be passed either as a String parameter or as a Supplier<String> parameter
Also note that despite the similar name, Spring assertions have nothing in common with the assertions of JUnit and other testing frameworks. Spring assertions aren’t for testing, but for debugging.
还要注意的是,尽管名称相似,但Spring断言与JUnit和其他测试框架的断言毫无共同之处。Spring断言不是用来测试的,而是用来调试的。
3. Example of Use
3.使用实例
Let’s define a Car class with a public method drive():
让我们定义一个汽车类,它有一个公共方法drive()。
public class Car {
private String state = "stop";
public void drive(int speed) {
Assert.isTrue(speed > 0, "speed must be positive");
this.state = "drive";
// ...
}
}
We can see how speed must be a positive number. The above row is a short way to check the condition and throw an exception if the condition fails:
我们可以看到速度必须是一个正数。上面这一行是检查条件的一个简短方法,如果条件失败,就抛出一个异常。
if (!(speed > 0)) {
throw new IllegalArgumentException("speed must be positive");
}
Each Assert’s public method contains roughly this code – a conditional block with a runtime exception from which the application is not expected to recover.
每个Assert的公共方法大致包含这样的代码–一个带有运行时异常的条件块,预计应用程序不会从中恢复。
If we try to call the drive() method with a negative argument, an IllegalArgumentException exception will be thrown:
如果我们试图用一个否定的参数来调用drive()方法,将会抛出一个IllegalArgumentException异常。
Exception in thread "main" java.lang.IllegalArgumentException: speed must be positive
4. Logical Assertions
4.逻辑性断言
4.1. isTrue()
4.1.isTrue()
This assertion was discussed above. It accepts a boolean condition and throws an IllegalArgumentException when the condition is false.
这个断言在上面讨论过。它接受一个boolean条件,当条件为假时抛出一个IllegalArgumentException。
4.2. state()
4.2.state()
The state() method has the same signature as isTrue() but throws the IllegalStateException.
state()方法的签名与isTrue()相同,但会抛出IllegalStateException。。
As the name suggests, it should be used when the method mustn’t be continued because of an illegal state of the object.
顾名思义,当方法因为对象的非法状态而不能继续时,就应该使用它。
Imagine that we can’t call the fuel() method if the car is running. Let’s use the state() assertion in this case:
想象一下,如果汽车正在运行,我们就不能调用fuel()方法。让我们在这种情况下使用state()断言。
public void fuel() {
Assert.state(this.state.equals("stop"), "car must be stopped");
// ...
}
Of course, we can validate everything using logical assertions. But for better readability, we can use additional assertions which make our code more expressive.
当然,我们可以使用逻辑断言来验证一切。但为了提高可读性,我们可以使用额外的断言,使我们的代码更具表现力。
5. Object and Type Assertions
5.对象和类型断言ns
5.1. notNull()
5.1.notNull()
We can assume that an object is not null by using the notNull() method:
我们可以通过使用notNull()方法假设一个对象不是null。
public void сhangeOil(String oil) {
Assert.notNull(oil, "oil mustn't be null");
// ...
}
5.2. isNull()
5.2.isNull()
On the other hand, we can check if an object is null using the isNull() method:
另一方面,我们可以使用isNull()方法检查一个对象是否为null。
public void replaceBattery(CarBattery carBattery) {
Assert.isNull(
carBattery.getCharge(),
"to replace battery the charge must be null");
// ...
}
5.3. isInstanceOf()
5.3.isInstanceOf()
To check if an object is an instance of another object of the specific type we can use the isInstanceOf() method:
要检查一个对象是否是另一个特定类型的对象的实例,我们可以使用isInstanceOf()方法。
public void сhangeEngine(Engine engine) {
Assert.isInstanceOf(ToyotaEngine.class, engine);
// ...
}
In our example, the check passes successfully as ToyotaEngine is a subclass of Engine.
在我们的例子中,由于ToyotaEngine是Engine.的一个子类,检查成功通过。
5.4. isAssignable()
5.4.isAssignable()
To check types, we can use Assert.isAssignable():
为了检查类型,我们可以使用 Assert.isAssignable()。
public void repairEngine(Engine engine) {
Assert.isAssignable(Engine.class, ToyotaEngine.class);
// ...
}
Two recent assertions represent an is-a relationship.
最近的两个论断代表了一种is-a关系。
6. Text Assertions
6.文本断言
Text assertions are used to perform checks on String arguments.
文本断言被用来对String参数进行检查。
6.1. hasLength()
6.1.hasLength()
We can check if a String isn’t blank, meaning it contains at least one whitespace, by using the hasLength() method:
我们可以通过使用hasLength()方法来检查一个字符串是否为空白,即它至少包含一个空格。
public void startWithHasLength(String key) {
Assert.hasLength(key, "key must not be null and must not the empty");
// ...
}
6.2. hasText()
6.2.hasText()
We can strengthen the condition and check if a String contains at least one non-whitespace character, by using the hasText() method:
我们可以通过使用hasText()方法来加强条件,检查String是否至少包含一个非空格字符。
public void startWithHasText(String key) {
Assert.hasText(
key,
"key must not be null and must contain at least one non-whitespace character");
// ...
}
6.3. doesNotContain()
6.3.doesNotContain()
We can determine if a String argument doesn’t contain a specific substring by using the doesNotContain() method:
我们可以通过使用doesNotContain()方法来确定String参数是否不包含一个特定的子串。
public void startWithNotContain(String key) {
Assert.doesNotContain(key, "123", "key mustn't contain 123");
// ...
}
7. Collection and Map Assertions
7.收集和地图断言
7.1. notEmpty() for Collections
7.1.notEmpty()用于集合
As the name says, the notEmpty() method asserts that a collection is not empty meaning that it’s not null and contains at least one element:
正如其名,notEmpty()方法断言一个集合不是空的,意味着它不是null并且至少包含一个元素。
public void repair(Collection<String> repairParts) {
Assert.notEmpty(
repairParts,
"collection of repairParts mustn't be empty");
// ...
}
7.2. notEmpty() for Maps
7.2.notEmpty()用于地图
The same method is overloaded for maps, and we can check if a map is not empty and contains at least one entry:
同样的方法被重载到地图上,我们可以检查一个地图是否为空并且至少包含一个条目。
public void repair(Map<String, String> repairParts) {
Assert.notEmpty(
repairParts,
"map of repairParts mustn't be empty");
// ...
}
8. Array Assertions
8.阵列断言
8.1. notEmpty() for Arrays
8.1.notEmpty()用于数组
Finally, we can check if an array is not empty and contains at least one element by using the notEmpty() method:
最后,我们可以通过使用notEmpty()方法来检查一个数组是否为空并且至少包含一个元素。
public void repair(String[] repairParts) {
Assert.notEmpty(
repairParts,
"array of repairParts mustn't be empty");
// ...
}
8.2. noNullElements()
8.2.noNullElements()
We can verify that an array doesn’t contain null elements by using the noNullElements() method:
我们可以通过使用noNullElements()方法来验证一个数组不包含空元素。
public void repairWithNoNull(String[] repairParts) {
Assert.noNullElements(
repairParts,
"array of repairParts mustn't contain null elements");
// ...
}
Note that this check still passes if the array is empty, as long as there are no null elements in it.
注意,如果数组是空的,只要其中没有null元素,这个检查仍然通过。
9. Conclusion
9.结语
In this article, we explored the Assert class. This class is widely used within the Spring framework, but we could easily write more robust and expressive code taking advantage of it.
在这篇文章中,我们探讨了Assert类。这个类在Spring框架中被广泛使用,但我们可以很容易地利用它写出更健壮、更有表现力的代码。
As always, the complete code for this article can be found in the GitHub project.
一如既往,本文的完整代码可以在GitHub项目中找到。