三种不通的注解
1. 字段级(field level) 约束
package com.mycompany; import javax.validation.constraints.NotNull; public class Car { @NotNull private String manufacturer; @AssertTrue private boolean isRegistered; public Car(String manufacturer, boolean isRegistered) { super(); this.manufacturer = manufacturer; this.isRegistered = isRegistered; } }
当约束被定义在字段上的时候, 这个字段的值是通过字段访问策略来获取并验证的. 也就是说Bean Validation的实现者会直接访问这个实例变量而不会调用属性的访问器(getter) 即使这个方法存在.
注意:这个字段的访问级别( private, protected 或者 public) 对此没有影响.
注意:静态字段或者属性是不会被校验的.
2.属性级别约束
package com.mycompany; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotNull; public class Car { private String manufacturer; private boolean isRegistered; public Car(String manufacturer, boolean isRegistered) { super(); this.manufacturer = manufacturer; this.isRegistered = isRegistered; } @NotNull public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } @AssertTrue public boolean isRegistered() { return isRegistered; } public void setRegistered(boolean isRegistered) { this.isRegistered = isRegistered; } }
注意:如果要定义约束在属性级别上的话,那么只能定义在访问器(getter)上面,不能定义在修改器(setter)上.
3.类级别约束
package com.mycompany; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @PassengerCount public class Car { @NotNull private String manufacturer; @NotNull @Size(min = 2, max = 14) private String licensePlate; @Min(2) private int seatCount; private List<Person> passengers; public Car(String manufacturer, String licencePlate, int seatCount) { this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; } //getters and setters ... }
最后,一个约束也能够被放在类级别上,当一个约束被标注在一个类上的时候,这个类的实例对象被传递给ConstraintValidator.当需要同时校验多个属性来验证一个对象或者一个属性在验证的时候需要另外的属性的信息的时候,类级别的约束很有用.在上面的例子中,我们给类Car添加了一个passengers的属性,疽我们还标注了一个PassengerCout约束在类级别上,稍后会看到我们是如何创建这个自定义约束的.现在我们可以知道这个标注会保证这个车里乘客的数量不会超过它的座位数
时间: 2024-11-15 20:04:54