@NotNull, @NotEmpty, @NotBlank of elegant verification parameters
First explain the difference between the three annotations:
annotation | effect | data type (in general) |
---|---|---|
@NotNull | It cannot be null, it can be empty (that is, it can be "") | Integer, Long, BigDecimal, Date (you can use @size, @Max, @Min, @Range to limit Integer) |
@NotEmpty | Cannot be null, and the length must be greater than 0 | collection, array |
@NotBlank | Not null, only works on String, and the length must be greater than 0 after calling trim(), that is, there must be actual characters | String (you can use @Length to limit the length) |
usage:
-
Write the corresponding parameter verification annotation on the attribute value of the entity class
public class UserRegisterDto implements Serializable { @NotBlank(message = "电话号码不可为空") @Schema(description = "电话号码", required = true) private String phone; @NotNull(message = "登录渠道不可为空") @Schema(description = "登录渠道", required = true) private Integer channel; }
-
Add the @@Valid annotation to the corresponding controller
public class UserRegisterController { @PostMapping("/register") @Operation(summary = "c端用户注册接口", description = "c端注册") public HttpResult<UserInfo> register(@RequestBody @Valid UserRegisterDto dto) { // TODO do something return HttpResult.success(userInfo); } }
**Note:** If the corresponding type is written incorrectly, an error will be reported. On my side, I wrote @NotEmpty on the channel field (Integer type), which resulted in the following error. Change it to @NotNull and it will be fine.
HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.Integer'. Check configuration for 'channel'