Java_Validation group verification

In the java development process, usually an object will be used in multiple interfaces, but each interface has different requirements for parameter verification. When this happens, we can use the method of group verification

Bean is written as follows

Add two interface classes, Add and AddFileType, in the verification part, add groups parameter configuration

@Data
public class FileInfo {
    
    @NotBlank(message = "文件id",groups = AddFileType.class)
    private Integer id;

    @NotBlank(message = "文件名称不能为空",groups = Add.class)
    private String fileName;

    @NotBlank(message = "文件类型不能为空",groups = AddFileType.class)
    private List<String> fileTypes;

    @NotBlank(message = "文件名称不能为空",groups = Add.class)
    private String filePath;
    
    private String fileDescribe;

    /**
     * 添加文件时生效
     */
    public interface Add{

    }
    /**
     * 添加文件类型时生效
     */
    public interface AddFileType{

    }
}

 Controller is written as follows

@Validated annotation plus the group to use

@RequestMapping(value = "/add", method = RequestMethod.POST)
public void addFile(@RequestBody @Validated({FileInfo.Add.class}) FileInfo fileInfo){
        //...
}

@RequestMapping(value = "/addType", method = RequestMethod.POST)
public void  addType(@RequestBody @Validated({FileInfo.AddType.class}) FileInfo fileInfo){
        //...
}

ok, so group verification can be realized~

Like it

Guess you like

Origin blog.csdn.net/weixin_40877388/article/details/126136872