Intro
最近,我专注于使用Spring Boot,Java和Swagger构建REST API。 我们都知道REST API涉及其中的Request和Response参数。 我对Java如何提供验证以防止重复的代码行感到惊讶。 在注释时代之前,我们总是使用如果别的指令。 如果此字段为null,则引发异常;如果A为null,则B成为强制性,依此类推。 假设您创建数百个涉及数百个字段参数的API?
Validation annotation
因此,Java为您提供了一个解决方案。 您可以将验证注释附加在字段中。 如果创建自定义验证,则也可以将其放在类级别。 我会记下最基本的一个。 以下是用于请求参数的字段验证的常用注释。
- @ NotBlank -> validates that value is not null. can be used in any type of field. usually String type
- @ Size -> validates size/length of value. Usually applied for integer type. It has attribute min and max
- @ Pattern -> to validate pattern using regex. I used this one a lot. It is very convenience to use other than comparing String with equals method. The challenge is creating the regex itself. You can simulate it here before use it. Probably I will write about this part in separate post.
Custom Validation
If your requirement getting complicated, and no basic annotation can accommodate it, you may create your own validation. This post is a good start .
I will share one of my custom validation later :D
Some example
@Pattern(regexp="^[0-9]*$")
@NotBlank
@Size(max = 20)
String myNumber;
@MyCustomValidation
String myCode;