简体   繁体   中英

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

{
    "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"

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

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

and add bean-validation annotations to your Json Object, for exmaple:

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

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

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 .

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.

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 ):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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