validation-api包校驗嵌套屬性(集合對象)的寫法

我們知道javax.validation提供了validation-api的jar包實現請求參數校驗,避免在業務代碼中寫一些繁瑣的校驗邏輯。
以下說明嵌套屬性的一種寫法。

package com.example.demo.controller;

import com.example.demo.model.ActionParentModel;
import com.example.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/hello")
public class DemoController {

@Autowired
private DemoService demoService;

@RequestMapping("/test")
public Boolean test(@RequestBody @Valid ActionParentModel req){
    return true;
}

}

ActionParentModel.class

package com.example.demo.model;

import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;

public class ActionParentModel implements Serializable {
    @Size(min = 1, max = 2)
    private List<List<@Valid ActionModel>> updateConds;

    public List<List<ActionModel>> getUpdateConds() {
        return updateConds;
    }

    public void setUpdateConds(List<List<ActionModel>> updateConds) {
        this.updateConds = updateConds;
    }
}

ActionModel .class

package com.example.demo.model;

import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

public class ActionModel {


    /**
     * 條件類型(1:寶馬,2:奔馳)
     */
    @NotNull
    @Range(min = 1, max = 2)
    private Integer keyType;

    @Pattern(regexp = "\\w+", message = "屬性名格式不正確")
    private String keyName;

    public Integer getKeyType() {
        return keyType;
    }

    public void setKeyType(Integer keyType) {
        this.keyType = keyType;
    }

    public String getKeyName() {
        return keyName;
    }

    public void setKeyName(String keyName) {
        this.keyName = keyName;
    }
}

List<List<@Valid ActionModel>> updateConds; 這裏的@Valid 必須放在ActionModel前面,否則校驗無效。

注意這裏的validation-api須爲2.0.1.Final,版本1.1.0.Final是不支持的。

對比兩個版本的源碼區別
2.0.1.Final:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Valid {
}

1.1.0Final:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Valid {
}

2.0.1.Final多了ElementType.TYPE_USE的支持。

maven依賴

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.0.16.Final</version>
</dependency>

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章