动态顺序校验(@GroupSequenceProvider)

Exisi 2022-06-28 22:51:12
Categories: Tags:
  • 除了通过 @GroupSequence 静态地重新定义默认组序列之外,Hibernate Validator还提供了一个注解,用于根据对象状态动态地重新定义默认组序列。

 

  • 为了实现动态地实现校验,需要实现接口 DefaultGroupSequenceProvider,并通过 @GroupSequenceProvider 注释将该实现注册到目标类。

 

参数

描述

value

继承了 DefaultGroupSequenceProvider 的类

示例

  • CustomGroupForm.java

 

@GroupSequenceProvider(value = CustomSequenceProvider.class)

public class CustomGroupForm {

 

@Pattern(regexp = "[A|B]" , message = "类型不必须为 A|B")

private String type;

 

@NotEmpty(message = "参数A不能为空" , groups = {WhenTypeIsA.class})

private String paramA;

 

@NotEmpty(message = "参数B不能为空", groups = {WhenTypeIsB.class})

private String paramB;

 

// standard constructors / setters / getters / toString

 

public interface WhenTypeIsA { }

 

public interface WhenTypeIsB { }

 

}

 

  • CustomSequenceProvider

public class CustomSequenceProvider implements DefaultGroupSequenceProvider<CustomGroupForm> {

@Override

public List<Class<?>> getValidationGroups(CustomGroupForm form) {

 

List<Class<?>> defaultGroupSequence = new ArrayList<>();

defaultGroupSequence.add(CustomGroupForm.class);

 

if (form != null && "A".equals(form.getType())) {

defaultGroupSequence.add(CustomGroupForm.WhenTypeIsA.class);

}

 

if (form != null && "B".equals(form.getType())) {

defaultGroupSequence.add(CustomGroupForm.WhenTypeIsB.class);

}

return defaultGroupSequence;

 

}

}

 

  • MainController.java

@Controller

Public class MainController(){

@PostMapping("/customGroup")
public ResultVo customGroup(@RequestBody @Validated CustomGroupForm form){
    return ResultVoUtil.success(form);
}

}

 

 

来自 <https://juejin.cn/post/6875316875950030855>