第一步、定义一个校验组类,声明四个接口对应不同场景校验
public class ValidationGroups {
public interface Update {
}
public interface Insert {
}
public interface Detail {
}
public interface Delete{
}
}
第二步、在实体类具体属性添加校验规则及校验分组
@Data
public class RegionRequest extends BaseRequest {
@NotNull(message = "渠道id 不能为空",groups ={ValidationGroups.Detail.class,ValidationGroups.GetList.class,ValidationGroups.Update.class})
private Integer regionId;
@NotBlank(message = "父渠道id 不能为空",groups ={ValidationGroups.Insert.class,ValidationGroups.Update.class})
private String superRegion;
}
第三步、在控制层@Validated注解后添加具体校验的分组名
@RequestMapping("/add")
@ResponseBody
private ResultHelper add(@RequestBody @Validated(ValidationGroups.Insert.class) RegionRequest regionRequest) throws InvocationTargetException, IllegalAccessException {
User loginUser = checkApiLoginUser(RequestUtil.getSessionId());
return ResultHelper.success();
}