简体   繁体   English

超类的条件Bean验证

[英]Conditional Bean Validation of Superclass

Use-case: When adding/editing an address or setting a direct delivery address the form has the same fields. 用例:添加/编辑地址或设置直接收信地址时,表单具有相同的字段。 So it's good practice to use the address form class as a super class of the delivery form: 因此,最好将地址表单类用作传递表单的超类:

public class AddressForm {
    @NotEmpty
    private String name;

    // ...
}

public class DeliveryForm extends AddressForm {
    public static enum ShippingType {
        DIRECT_SHIPPING,
        // ...
    }

    @NotNull
    private ShippingType shippingType;
    // ...
}

Is it possible to create a custom constraint (validator) at class level to set the condition whether the super class should be validated or not? 是否可以在类级别创建自定义约束(验证器)来设置是否应验证超类的条件?

Such as: 如:

@ValidateSuperclassIf(field = "shippingType", value = "DIRECT_SHIPPING")
public class DeliveryForm extends AddressForm {
    // ...
}

How to implement the javax.validation.ConstraintValidator<ValidateSuperclassIf, Object>.isValid(Object value, ConstraintValidatorContext context) method then? 那么如何实现javax.validation.ConstraintValidator<ValidateSuperclassIf, Object>.isValid(Object value, ConstraintValidatorContext context)方法呢?

Is it possible to create a custom constraint (validator) at class level to set the condition whether the super class should be validated or not? 是否可以在类级别创建自定义约束(验证器)来设置是否应验证超类的条件?

No, you cannot. 你不能。 There are not means in Bean Validation (the spec) nor in the reference implementation Hibernate Validator to do so. Bean验证(规范)或参考实现Hibernate Validator中都没有这样做的手段。

There are some discussions to have the ability to skip super type constraints ( HV-548 and BVAL-256 ), but that would just generally disable them, not add conditional (de-)activiation. 有一些讨论可以跳过超类型约束( HV-548BVAL-256 ),但是通常只会禁用它们,而不添加条件(取消激活)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM