Issue
I have a rest request entity in spring boot controller define like this:
package com.dolphin.rpa.application.command.credential;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author xiaojiang.jiang
* @date 2022/05/10
**/
@Data
public class CredentialDeleteCommand {
@NotNull(message = "should not be null")
private List<Long> ids;
@Min(1)
@Max(2)
private Integer mode;
}
Now I want to make sure the ids should not be null or size eqauls 0. I have tried these way:
@NotNull(message = "should not be null")
@NotEmpty(message = "should not be null")
@NotBlank(message = "should not be null")
But could not work. I also read the official docs that did not mentioned valid the List. Is it possible to valid the List elemnts? This is my reqeust json:
{
"ids": [
],
"mode": 1
}
Solution
Just adding @Size(min=1)
is enough.
@Data
public class CredentialDeleteCommand {
@NotNull(message = "should not be null")
@Size(min=1)
private List<Long> ids;
@Min(1)
@Max(2)
private Integer mode;
}
The error is probably where you call this object to be validated. It must certainly be on some method from an instance that belongs to spring. So it should be a bean of spring container.
Normally you will use this in some method of the controller, as the controller already belongs to spring container.
@RequestMapping(path="/some-path",method=RequestMethod.POST)
public ResponseEntity doSomething(@Valid @RequestBody CredentialDeleteCommand credentialDeleteCommand){
....
}
Keep in mind though that @Valid
should be placed before @RequestBody
otherwise it does not work. At least in previous spring versions that I have faced this issue.
Answered By – Panagiotis Bougioukos
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0