How to use validator in Spring Boot to implement automatic verification of interface parameters

Article directory

1. Background

During the project development process, some fields are often verified, such as field non-empty verification, field length verification, etc. If you write a bunch of if else in every required place, your code will become redundant. It is bulky and relatively difficult to maintain. How can we make the verification more standardized and elegant?

In Spring Boot, you can use Validation Api and Hibernate Validator to implement automatic verification of interface parameters.

2. Use

1. If the member variable is another object entity, the variable must be added ​​@Valid​​, otherwise the nested verification will not take effect.

2. Add dependencies: Spring Boot project project dependencies, because validation-api and hibernate-validator are already included in spring-boot-starter-web, so no additional references are needed.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/>
</parent>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Maven project depends on maven

  <dependency>
        <groupId>jakarta.validation</groupId>
        <artifactId>jakarta.validation-api</artifactId>
    </dependency>

3. First, you need to understand the role of the three non-null constraint annotations under javax.validation: @NotNull, @NotEmpty, @NotBlank

constraint illustrate
@NotNull Acts on Integer (including other basic classes). After adding @NotNull constraint to the Integer attribute, the attribute cannot be null and there is no size constraint; @NotNull acts on Collection, Map or collection object, and the collection object cannot be null, but it can be an empty set, that is, size=0 (generally use @NotEmpty constraints on collection objects)
@NotBlank It only works on String. After adding @NotBlank constraint to the String attribute, the attribute cannot be null and size>0 after trim().
@NotEmpty @NotEmpty works on collection classes. After @NotEmpty constraints are added to Collection, Map, and arrays, the collection object cannot be null and cannot be an empty set, that is, size>0

3. Examples

Controller class:

public class CustomerSyncController {
    
    

    /**
     * 客户同步
     */
    @ApiOperation(value = "客户同步")
    @PostMapping(value = "/customer/sync")
    public Result<Boolean> syncCustomerInfo(@RequestBody @Valid CustomerInfoVo paramVos) {
    
    
        try {
    
    
            if (!ObjectUtils.isEmpty(paramVos)) {
    
    
                customerInfoService.syncCustomerInfo(paramVos);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
            log.error("[syncCustomerInfo] request error,paramVos:{},异常:{}", paramVos, e.getMessage());
            return Result.error(BasicCodeMsg.SERVER_ERROR);
        }
        return Result.success(Boolean.TRUE);
    }
}

Entity class:

@NoArgsConstructor
@Data
public class CustomerInfoVo implements Serializable {
    
    

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "客户id")
    @NotBlank(message = "客户ID不能为空")
    private String customerId;

    @ApiModelProperty(value = "客户姓名")
    @NotBlank(message = "客户姓名不能为空")
    private String name;

    @ApiModelProperty(value = "证件类型")
    @NotNull(message = "证件类型不能为空")
    private Integer certificateType;

    @ApiModelProperty(value = "证件号")
    @NotBlank(message = "证件号不能为空")
    private String certificate;
    }

Just test it with postman.
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_47061482/article/details/131958707