java Bean 验证组 - 正确理解它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17475756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:06:52  来源:igfitidea点击:

Bean Validation Groups - Understanding it correctly

javajavabeansbean-validation

提问by Kevin Rave

I am trying to understand the Groups in Bean validation.

我试图了解 Bean 验证中的组。

So for instance if I have a bean and I want only certain field validated for certain cases, I should group them?

因此,例如,如果我有一个 bean 并且我只想在某些情况下验证某些字段,我应该将它们分组吗?

 @NotNull (groups=MyClassX.class)
 @Min (groups=MyClassA.class)  // 1
 @Pattern(xxxxx, groups = MyClassA.class) // 2
 private String field1;

 @NotNull (groups=MyClassX.class)
 @Min (groups=MyClassX.class)
 @Pattern(xxxxx, groups=MyClassX.class))
 private String field2;

 @NotNull (groups=MyClassX.class)
 @Min (groups=MyClassX.class)
 @Pattern(xxxxx, groups=MyClassA.class) //3
 private String field3;

My understanding from the above example is, if I pass MyClassAto validator, then only @Minand @Patternfor Field1and @Patternfor field3are only validated? (marked with numbers 1,2 and 3)

我从上面的例子中的理解是,如果我传递MyClassA给验证器,那么 only@Min@PatternforField1@Patternforfield3只被验证?(标有数字 1,2 和 3)

Did I understand this correctly? I haven't left any fields without Groupsattribute. So no default group.

我理解正确吗?我没有留下任何没有Groups属性的字段。所以没有默认组。

采纳答案by Arnaud Denoyelle

First, here is the javax.validation javadoc

首先,这里是javax.validation javadoc

When you want to validate a bean, you actually call Validator.validate(T object, java.lang.Class... groups)

当你想验证一个 bean 时,你实际上调用了Validator.validate(T object, java.lang.Class... groups)

It will then check the validations constraints of the specified groups. It allows to use several validation cases.

然后它将检查指定组的验证约束。它允许使用多个验证案例。

What you describe in your question is accurate.

您在问题中描述的内容是准确的。

Note, if you do not put any group on your constraints, then the constraints belong to the default group, which is the only validated group if you don't specify any group when calling validate(T object).

请注意,如果您没有在约束上放置任何组,则约束属于默认组,如果您在调用 validate(T object) 时未指定任何组,则该组是唯一经过验证的组。