Hibernate Validator 提供了"根据对象状态动态重定义默认分组"的接口。
什么意思呢?考虑下面这个场景:假如一个bean有3个属性,分别是attrA, attrB和attrC。当attrA属性的值是value1,我们需要对attrB进行校验;当attrA属性的值是value2的时候,我们需要对attrC进行校验。为了实现上面这个目的,我们需要实现DefaultGroupSequenceProvider接口,并且在被校验的bean上使用@GroupSequenceProvider来应用我们的实现。
- 自定义分组序列提供器
import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider;
import org.springblade.modules.presetActionTemplate.dto.PresetActionTemplateParams;
import java.util.ArrayList;
import java.util.List;
public class PresetActionTemplateParamsProvider implements DefaultGroupSequenceProvider<PresetActionTemplateParams> {
@Override
public List<Class<?>> getValidationGroups(PresetActionTemplateParams params) {
List<Class<?>> defaultGroupSequence = new ArrayList<>();
defaultGroupSequence.add(PresetActionTemplateParams.class);
if (params != null && params.getType() != null) {
if (params.getType() == 0) {
defaultGroupSequence.add(PresetActionTemplateParams.SaveTypeOne.class);
}
}
return defaultGroupSequence;
}
}
- 待校验的bean
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.group.GroupSequenceProvider;
import org.springblade.modules.presetActionTemplate.provider.PresetActionTemplateParamsProvider;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* 溯源参数
*
* @author BladeX
* @since 2024-02-19
*/
@Data
@GroupSequenceProvider(value = PresetActionTemplateParamsProvider.class)
public class PresetActionTemplateParams {
@NotBlank(message = "id不能为空", groups = Update.class)
@ApiModelProperty(value = "id")
private String id;
@NotBlank(message = "模版名称不能为空")
@NotBlank(message = "模版名称不能为空", groups = Save.class)
@ApiModelProperty(value = "模版名称")
private String name;
@NotBlank(message = "开放资源ID不能为空", groups = SaveTypeOne.class)
@ApiModelProperty(value = "开放资源ID(对外开放使用)")
private String openSourceId;
@NotNull(message = "类型不能为空")
@NotNull(message = "类型不能为空", groups = Save.class)
@ApiModelProperty(value = "类型 0 默认 1 自定义")
private Integer type;
@ApiModelProperty(value = "备注")
private String remark;
public interface Save {
}
public interface Update {
}
public interface Detail {
}
public interface Remove {
}
public interface SaveTypeOne {
}
}
- 测试
/**
* 新增 预设动作模版
*/
@PostMapping("/save")
@ApiOperationSupport(order = 4)
@ApiLog("预设动作模版新增")
@ApiOperation(value = "新增", notes = "传入presetActionTemplate")
public R save(@Validated @RequestBody PresetActionTemplateParams params) {
return R.status(presetActionTemplateService.save(params));
}
- 执行结果
-
无任何参数
-
有必填参数为空
-
类型为0
4.类型为1