简体   繁体   English

springboot中的bean验证

[英]Bean validation in springboot

public class test{
    private String id;
    private String status;
    private Integer alertsCount
    }

I have a class test, when a rest api implemented using springboot with post request gets triggered input json looks like我有一个 class 测试,当 rest api 使用 springboot 实现时,带有发布请求的触发输入 Z466DEEC76ECDF5FCA6D385

{
    "id": "1",
    "status": "Cancelled",
    "alertCount": 10
    }

at my model class i need to add restriction to prevent status to be one of the below values "Successfull", "Cancelled", "In Progress", "On Hold"在我的 model class 我需要添加限制以防止状态为以下值之一“成功”、“取消”、“进行中”、“暂停”

How can i achieve this.我怎样才能做到这一点。

Add Dependency添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

then add @Valid to your Request Handler Method parameter然后将@Valid添加到您的请求处理程序方法参数

@PostMapping("/test/")
ResponseEntity<String> addTest(@Valid @RequestBody Test test) {
    return ResponseEntity.ok();
}

and add bean-validation annotations to your Json Object, for exmaple:并向您的 Json Object 添加 bean 验证注释,例如:

public class Test{
    @NotNull
    private String id;
    @NotNull
    @Pattern(regexp="(Successfull)|(Cancelled)|(In Progress)|(On Hold)")
    private String status;
    @NotNull
    private Integer alertsCount
    }

Some other example: https://stackoverflow.com/a/9994590/280244 that also contains the handling of validation errors, via BindingResult其他一些示例: https://stackoverflow.com/a/9994590/280244 ,其中还包含验证错误的处理,通过BindingResult

BTW: An other idea is to use an Enum instead of an String (that causes other Exception when the string does not match!) but then the whitespace must been replaced)顺便说一句:另一个想法是使用枚举而不是字符串(当字符串不匹配时会导致其他异常!)但是必须替换空格)

@Pattern(regexp = "^(Successfull)|(Cancelled)|(In Progress)|(On Hold)$" 
private String status;

DON'T FORGET TO USE @Valid AT CONTROLLER不要忘记使用@Valid AT CONTROLLER

What about using Enums?使用枚举怎么样? This decision is clean and simple.这个决定是干净和简单的。

public class test{
    private String id;
    private STATUS status;
    private Integer alertsCount
}

public enum STATUS {
    public Successfull;
    public Cancelled;
    public InProgress;
    public OnHold
}

Write your custom ConstraintValidator .编写您的自定义ConstraintValidator

Since status field has to have value from predefined set of constants , it would be better to provide an enum containing all available status strings.由于status字段必须具有来自预定义常量集的值,因此最好提供一个包含所有可用状态字符串的枚举。

public class TestModel{

    private String id;
    private StatusEnum status;
    private Integer alertsCount;

}

public enum StatusEnum {

    SUCCESSFUL("Successful"),
    CANCELLED("Cancelled"),
    IN_PROGRESS("In progress"),
    ON_HOLD("On hold");
    
    private String statusTag;

    StatusEnum(String status){
        this.statusTag = status;
    }

}

Enums are designed for exactly such situations, according to Java documentation ( https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html ): Enums are designed for exactly such situations, according to Java documentation ( https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html ):

An enum type is a special data type that enables for a variable to be a set of predefined constants.枚举类型是一种特殊的数据类型,它使变量能够成为一组预定义的常量。 The variable must be equal to one of the values that have been predefined for it.该变量必须等于为其预定义的值之一。 Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.常见示例包括指南针方向(NORTH、SOUTH、EAST 和 WEST 的值)和星期几。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM