引入依赖
<!-- validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
定义分组接口
public interface AddGroup {
}
public interface UpdateGroup {
}
定义入参DTO
package vip.xiaonuo.sys.modular.cg.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import vip.xiaonuo.common.validator.groups.AddGroup;
import vip.xiaonuo.common.validator.groups.SubclassGroup;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;
/**
* @author ikun
* @version v1.0.0
* @since 2024/1/8 11:13
**/
@Data
public class BuyRegisterDTO {
@NotNull(message = "申请部门id不能为空", groups = {AddGroup.class})
@ApiModelProperty("申请部门id")
private String registerDeptId;
@NotNull(message = "产品集合不能为空", groups = {AddGroup.class})
@ApiModelProperty("产品集合")
private List<ProductDTO> productDTOList;
@Data
@ApiModel("登记产品")
public static class ProductDTO{
@NotNull(message = "产品id不能为空", groups = {AddGroup.class})
@ApiModelProperty("产品id")
private Long productId;
@NotNull(message = "申请采购数量不能为空", groups = {AddGroup.class})
@ApiModelProperty("申请采购数量")
private BigDecimal applyCount;
@NotNull(message = "申请采购计量数量不能为空", groups = {AddGroup.class})
@ApiModelProperty("申请采购计量数量")
private BigDecimal applyMeasureCount;
@NotNull(message = "预估单价不能为空", groups = {AddGroup.class})
@ApiModelProperty("预估单价")
private BigDecimal forecastUnitPrice;
@ApiModelProperty("申请理由")
private String applyReason;
@ApiModelProperty("具体要求")
private String realRequire;
}
}
定义工具类
package vip.xiaonuo.common.validator;
import org.springframework.util.CollectionUtils;
import vip.xiaonuo.common.exception.CommonException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
/**
* hibernate-validator校验工具类
*
* 参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
*
* @author lyf
*
* @date 2017-03-15 10:50
*/
public class ValidatorUtils {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* 校验对象
* @param object 待校验对象
* @param groups 待校验的组
* @throws CommonException 校验不通过,则报RRException异常
*/
public static void validateEntity(Object object, Class<?>... groups)
throws CommonException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for(ConstraintViolation<Object> constraint: constraintViolations){
msg.append(constraint.getMessage()).append("\n");
}
throw new CommonException(msg.toString());
}
}
/**
* 校验集合
* @param list
* @param groups
*/
public static void validateList(List<?> list, Class<?>... groups) {
if (CollectionUtils.isEmpty(list)) {
return;
}
list.forEach(e -> validateEntity(e, groups));
}
}
调用工具类
@Api(tags = "宏茂端-采购-采购登记")
@RestController
@RequestMapping("/cg/buyRegister")
public class BuyRegisterController {
@Autowired
private BuyRegisterService buyRegisterService;
@ApiOperation("新增")
@PostMapping("/save")
public CommonResult save(@RequestBody BuyRegisterDTO buyRegisterDTO) {
ValidatorUtils.validateEntity(buyRegisterDTO, AddGroup.class);
List<BuyRegisterDTO.ProductDTO> productDTOList = buyRegisterDTO.getProductDTOList();
ValidatorUtils.validateList(productDTOList, AddGroup.class);
buyRegisterService.doSave(buyRegisterDTO);
return CommonResult.data(null);
}
}
第二种
参数范围限制
package vip.xiaonuo.sys.modular.basics.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import vip.xiaonuo.common.util.NoNullUtil.AddGroup;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Data
public class AddUser implements Serializable {
@NotBlank(message = "名字不能为空!")
private String name;
@Min(value = 0,message = "年龄不能为负数")
@Max(value = 150,message = "年龄参数异常")
private Integer ago;
}
@ApiOperationSupport(order = 10)
@ApiOperation("添加用户")
@CommonLog("添加用户")
@PostMapping("/add")
@SaCheckPermission
public CommonResult addUnit(
@RequestBody @Valid AddJob addJob) {
jobService.addJob(addJob);
return CommonResult.ok();
}
![](https://i-blog.csdnimg.cn/blog_migrate/19d6b7d77218d42f008c0655731681ea.png)
![](https://i-blog.csdnimg.cn/blog_migrate/bc17a4cc27d6e06f955c0ae65ae0f576.png)
![](https://i-blog.csdnimg.cn/blog_migrate/29837b24ec252766cccdc55f50936a75.png)
自定义参数范围
1 添加枚举
package vip.xiaonuo.common.util.ParameterRange;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 枚举校验注解
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {
// 默认错误消息
String message() default "必须为指定值";
String[] strValues() default {};
int[] intValues() default {};
// 分组
Class<?>[] groups() default {};
// 负载
Class<? extends Payload>[] payload() default {};
// 指定多个时使用
@Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List {
EnumValue[] value();
}
}
2 添加校验枚举处理类
package vip.xiaonuo.common.util.ParameterRange;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 枚举校验注解处理类
*/
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
private String[] strValues;
private int[] intValues;
@Override
public void initialize(EnumValue constraintAnnotation) {
strValues = constraintAnnotation.strValues();
intValues = constraintAnnotation.intValues();
}
//并且必须非空 若要取消非空限定 判断 value为空返回true即可
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
//if (!ObjectUtils.isEmpty(value)){
if (value instanceof String) {
for (String s : strValues) {
if (s.equals(value)) {
return true;
}
}
} else if (value instanceof Integer) {
for (int s : intValues) {
if (s == ((Integer) value).intValue()) {
return true;
}
}
}
return false;
//}
//return true;
}
}
3 使用
package vip.xiaonuo.sys.modular.basics.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import vip.xiaonuo.common.util.ParameterRange.EnumValue;
import java.io.Serializable;
@Data
public class AddJob implements Serializable {
@ApiModelProperty("是否能操作数据 -1:不能 1:能")
@EnumValue(intValues = {-1,1},message = "是否能操作数据只能是-1或1")
private Integer isOperation;
@ApiModelProperty("文章类型")
@EnumValue(strValues = {"blog", "photo"}, message = "文章类型只能是blog或者photo")
private String type;
}
@Valid
@ApiOperationSupport(order = 10)
@ApiOperation("添加工作")
@CommonLog("添加工作")
@PostMapping("/add")
@SaCheckPermission
public CommonResult addUnit(
@RequestBody @Valid AddJob addJob) {
ValidatorUtils.validateEntity(addJob, AddGroup.class);
jobService.addJob(addJob);
return CommonResult.ok();
}