新建一个类,用于分组:
import javax.validation.groups.Default;
public class ValidationGroups {
public interface Add extends Default {}
public interface Update extends Default {}
}
使用方式:
controller中:
public BaseResponse<Boolean> update(@RequestBody @Validated(ValidationGroups.Update.class) ParamVO paramVO){
return BaseResponse.success(True);
}
在paramVO的配置:
public class ParamVO {
@NotNull(groups = ValidationGroups.Update.class)
private Long id;
@NotNull(groups = ValidationGroups.Add.class)
private String name;
}
扩展
还可以对hibernate Validated自带的注解进行排序校验,但是这种情况会使上述分组失效,需要将新增和编辑写成不同的类(即每个方法都需要一个参数类)。使用方法如下: 自定义接口:
import org.hibernate.validator.constraints.Length;
import javax.validation.GroupSequence;
import javax.validation.constraints.*;
@GroupSequence({NotNull.class, NotBlank.class, Size.class, Length.class, Pattern.class, Max.class, Min.class})
public interface ValidationSequence {
}
使用方式:
controller中:
@PostMapping("/add")
public BaseResponse<Boolean>
add(@RequestBody @Validated(value = {ValidationSequence.class}) AddParamVO paramVO)
throws ServiceException {
return BaseResponse.success(True);
}
|