hibernate验证器中字段的短路约束

时间:2011-10-15 15:41:16

标签: annotations hibernate-validator

我希望对类的字段的约束进行排序和短路,例如

@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约束失败,因此甚至不会检查下一个约束。我浏览了群组,GroupSequence和复合约束,但似乎没有任何用处。具体来说,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)

我希望name上的第一个约束和noOfDependants上的第二个约束失败。但是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

1 个答案:

答案 0 :(得分:1)

如您所链接的问题中所述,只能存在具体注释类型的注释成员,因此您无法以预期的方式实现@LazySequence

我不确定你所说的“短路”是什么意思,但根据你的描述,我认为使用群组序列仍然应该有效:

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;

}

现在使用定义的序列(Bean)验证validator.validate(bean, Sequence.class)实例时,首先会验证@Size约束,并且只有在@Pattern约束成功后才会验证{{1}}约束。

您可以在Bean验证specification和Hibernate验证器reference guide中了解有关验证组和组序列的更多信息。