我希望对类的字段的约束进行排序和短路(例如,休眠验证器中的字段上的短路约束
@Size(min = 2, max = 10, message = "Name length improper")
@Pattern(regexp = "T.*", message = "Name doesn't start with T")
private String name;
与name="S"
,应该失败@Size
约束,因此,即使不用检查下一个。我经历了Groups,GroupSequence
和Composite Constraints,但似乎没有什么用处。具体来说,GroupSequence
不适用于我的情况。试想一下:
public class Bean {
public interface First{}
public interface Second {}
@GroupSequence({First.class, Second.class})
public interface Sequence {}
public Bean(String name, int noOfDependants) {
...
}
@Size(min = 2, max = 10, groups = {First.class})
@Pattern(regexp = "T.*", groups = {Second.class})
private String name;
@Min(value = 0, groups = {First.class})
@Max(value = 4, groups = {Second.class})
private int noOfDependants;
}
validator.validate(new Bean("S", 5), Sequence.class)
我期望在noOfDependants
上name
第一约束和第二约束失败。但是GroupSequence的工作方式,First.class组会失败,Second.class甚至不会被执行。
最后,我决定写我自己的约束,像这样:
@LazySequence({
@Size(min = 2, max = 10, message = "Name length improper"),
@Pattern(regexp = "T.*", message = "Name doesn't start with T")
})
private String name;
,并击中了熟悉的问题Annotation member which holds other annotations?
public @interface LazySequence {
???[] values();
String message() default "";
...
}
有没有人遇到这种使用情况?
THX
我已经更新了上面的示例来解释为什么GroupSequence不能解决我的问题。 – Tushar
但是,难道你不能只是改变'@ Max'和'@ Min'的限制吗?在验证“@ Sequence”组序列时,首先会对“@ Size”和“@ Max”进行验证,然后是“@ Pattern”和“@ Min”。 – Gunnar
我想维护一个字段上约束的顺序,例如我想'@ Min'在'@ Max'之前执行。也许这个人为的例子并不能证明我的需要。基本上我需要对每个领域的“排序”以及“懒惰”/“失败 - 快速”(无论您选择调用它)约束检查。 – Tushar