问题
I want the constraints on fields of a class to be ordered and short-circuit, e.g.
@Size(min = 2, max = 10, message = "Name length improper")
@Pattern(regexp = "T.*", message = "Name doesn't start with T")
private String name;
with name="S"
, should fail the @Size
constraint and hence not even bother checking the next one. I went through Groups, GroupSequence
and Composite Constraints but nothing seems to be of use. Specifically, GroupSequence
will not work for my case. Consider this:
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)
I expect the first constraint on name
and second constraint on noOfDependants
to fail. But the way GroupSequence works, the First.class group would fail and Second.class wouldn't even be executed.
Finally, I decided to write my own constraint like so:
@LazySequence({
@Size(min = 2, max = 10, message = "Name length improper"),
@Pattern(regexp = "T.*", message = "Name doesn't start with T")
})
private String name;
and hit the familiar problem Annotation member which holds other annotations?
public @interface LazySequence {
???[] values();
String message() default "";
...
}
Has anyone encountered this use case?
Thx
回答1:
As outlined in the question you linked, there can only be annotation members of a concrete annotation type, so there is no way you could implement @LazySequence
in the intended way.
I'm not exactly sure what you mean by "short-circuit", but based on your description I think using group sequences still should work:
public class Bean {
public interface First {}
public interface Second {}
@GroupSequence({First.class, Second.class})
public interface Sequence {}
@Size(min = 2, max = 10, message = "Name length improper", groups = { First.class })
@Pattern(regexp = "T.*", message = "Name doesn't start with T" , groups = { Second.class })
private String name;
}
When now validating a Bean
instance using the defined sequence (validator.validate(bean, Sequence.class)
), at first the @Size
constraint will be validated and only if that succeeds the @Pattern
constraint.
You can learn more about validation groups and group sequences in the Bean Validation specification and the Hibernate Validator reference guide.
来源:https://stackoverflow.com/questions/7778815/short-circuiting-constraints-on-a-field-in-hibernate-validator