gpt4 book ai didi

java - 列表的 Bean 验证大小?

转载 作者:太空狗 更新时间:2023-10-29 22:34:21 29 4
gpt4 key购买 nike

如何设置 List 应至少包含 1 个元素且最多包含 10 个元素的 bean 验证约束?

以下均无效:

@Min(1)
@Max(10)
@Size(min=1, max=10)
private List<String> list;

最佳答案

我创建了简单的类:

public class Mock {

@Size(min=1, max=3)
private List<String> strings;

public List<String> getStrings() {
return strings;
}

public void set(List<String> strings) {
this.strings = strings;
}

}

并测试:

Mock mock = new Mock();
mock.setStrings(Collections.emptyList());
final Set<ConstraintViolation<Mock>> violations1 = Validation.buildDefaultValidatorFactory().getValidator().validate(mock);
assertFalse(violations1.isEmpty());

mock.setStrings(Arrays.asList("A", "B", "C", "D"));
final Set<ConstraintViolation<Mock>> violations2 = Validation.buildDefaultValidatorFactory().getValidator().validate(mock);
assertFalse(violations2.isEmpty());

@Size 注释似乎运行良好。它来自 javax.validation.constraints.Size

关于java - 列表的 Bean 验证大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108805/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com