JSR 303:如何验证带注释的对象集合?
是否可以在 JSR 303 - Jave Bean Validation 中验证对象集合,其中集合本身没有任何注释,但其中包含的元素有?
例如,这是否可能由于第二人的名称为空而导致违反约束:
List<Person> people = new ArrayList<Person>();
people.add(new Person("dave"));
people.add(new Person(null));
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<List<Person>>> validation = validator.validate(people);
Is it possible to validate a collection of objects in JSR 303 - Jave Bean Validation where the collection itself does not have any annotations but the elements contained within do?
For example, is it possible for this to result in a constraint violation due to a null name on the second person:
List<Person> people = new ArrayList<Person>();
people.add(new Person("dave"));
people.add(new Person(null));
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<List<Person>>> validation = validator.validate(people);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,只需将
@Valid
添加到集合中即可。这是 Hibernate 验证器的示例参考。
这是标准 JSR-303 行为。请参阅规范的第 3.1.3 节。
Yes, just add
@Valid
to the collection.Here is an example from the Hibernate Validator Reference.
This is standard JSR-303 behavior. See Section 3.1.3 of the spec.
您还可以将
@NotEmpty
添加到集合中。这将确保至少有一名乘客在场,并且
@Valid
注释可确保每个Person
对象都经过验证You, can also add
@NotEmpty
to the collection.this will ensure at least one passenger is present, and the
@Valid
annotation ensures that eachPerson
object is validated从 Bean Validator 2.0 开始,这两种方法都有效
:
As of Bean Validator 2.0, both of these approaches work:
and
当然,您也可以迭代列表并对每个元素调用 Validator.validate。或者将 List 放入某个包装器 bean 中并使用 @Valid 对其进行注释。扩展 ArrayList 进行验证对我来说似乎是错误的。
您有想要用此解决的特定用例吗?如果是这样,也许你可以多解释一下。回答你最初的问题:
不
You can of course also just iterate over the list and call Validator.validate on each element. Or put the List into some wrapper bean and annotate it with @Valid. Extending ArrayList for validation seems wrong to me.
Do you have a particular use case you want to solve with this? If so maybe you can explain it a little more. To answer your initial question:
No
我写了这个通用类:
如果您使用 Jackson 库来反序列化 JSON,您可以在构造函数上添加 @JsonCreator 注释,Jackson 会自动将 JSON 数组反序列化为包装对象。
I wrote this generic class:
If you are using Jackson library to deserialize JSON you can add
@JsonCreator
annotation on the constructor and Jackson will automatically deserialize JSON array to wrapper object.