1. 程式人生 > >Hibernate Validator 6.0.7.Final 之三(方法約束之級聯約束)

Hibernate Validator 6.0.7.Final 之三(方法約束之級聯約束)

bean屬性約束之級聯約束一樣,方法約束也支援級聯約束。直接看例子:

  • Car定義
public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;

    public Car(String manufacturer, String licencePlate) {
        this.manufacturer = manufacturer;
        this
.licensePlate = licencePlate; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getLicensePlate() { return licensePlate; } public void
setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } }
  • Garage定義
public class Garage {

    @NotNull
    private String name;

    // 返回值約束
    @Valid
    public Garage(String name) {
        this.name = name;
    }

    // 引數約束
    public boolean checkCar(@Valid @NotNull Car car) {
        return
false; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

在上面的例子中,當驗證checkCar方法的引數的時候,定義在car物件上的約束也會被計算。同樣的,當驗證Garage構造方法的返回值的時候,Garage物件的name屬性上的@NotNull約束也會被計算。
總之,方法約束和普通屬性約束類似,也支援級聯約束,具體細節可以參考普通屬性的級聯約束