Spring Boot中使用validator如何实现接口入参自动检验

一、背景

在项目开发过程中,经常会对一些字段进行校验,比如字段的非空校验、字段的长度校验等,如果在每个需要的地方写一堆if else 会让你的代码变的冗余笨重且相对不好维护,如何更加规范和优雅的校验呢?

Spring Boot中可以使用Validation Api和Hibernate Validator实现接口入参自动检验。

二、使用

1、如果成员变量是其他对象实体,该变量必须加 ​​@Valid​​,否则嵌套中的验证不生效

2、添加依赖:Spring Boot项目工程依赖,因为在spring-boot-starter-web中已经包含了validation-api和hibernate-validator,所以无需再额外引用

<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项目工程依赖maven

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

3、首先需要了解javax.validation下的三个非空约束注解的作用位置:@NotNull、@NotEmpty、@NotBlank

约束 说明
@NotNull 作用在Integer上(包括其它基础类),在Integer属性上加上@NotNull约束后,该属性不能为null,没有size的约束;@NotNull作用在Collection、Map或者集合对象上,该集合对象不能为null,但可以是空集,即size=0(一般在集合对象上用@NotEmpty约束)
@NotBlank 只作用在String上,在String属性上加上@NotBlank约束后,该属性不能为null且trim()之后size>0
@NotEmpty @NotEmpty 作用在集合类上面,在Collection、Map、数组上加上@NotEmpty约束后,该集合对象是不能为null的,并且不能为空集,即size>0

三、举例

Controller类:

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);
    }
}

实体类:

@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;
    }

用postman测试即可。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47061482/article/details/131958707