bil*_*.cn 5 java hibernate-validator
我使用 Hibernate Validator (HV) 作为我的 JSR 303 验证器。然而,在 JSR 303 和 HV 的扩展中,似乎没有任何注释来指定约束,例如键必须存在于 Map 中或仅验证与键对应的 Map 值。
我的用例是,仅当 bean 的某些其他属性设置为 true 时,某些映射键才需要具有有效值。目前,我使用了一个假 getter 和一个 @AssertTrue 注释,但我真的很想让它更加基于注释。
似乎没有任何注释来指定约束,例如映射中必须存在键。
这可以通过实现自定义约束来解决:
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { ContainsKeyValidator.class })
public @interface ContainsKeys {
String message() default "{com.acme.ContainsKey.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String[] value() default {};
}
Run Code Online (Sandbox Code Playgroud)
还有一个像这样的验证器:
public class ContainsKeysValidator implements ConstraintValidator<ContainsKeys, Map<?, ?>> {
String[] requiredKeys;
@Override
public void initialize(ContainsKeys constraintAnnotation) {
requiredKeys = constraintAnnotation.values();
}
@Override
public boolean isValid(Map<?, ?> value, ConstraintValidatorContext context) {
if( value == null ) {
return true;
}
for( String requiredKey : requiredKeys ) {
if( value.containsKey( requiredKey ) ) {
return false;
}
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
我的用例是,仅当 bean 的某些其他属性设置为 true 时,某些映射键才需要具有有效值。
对于这个要求,您可以实现一个类级约束,它允许在验证器实现中访问完整的 bean 及其所有属性。
| 归档时间: |
|
| 查看次数: |
7553 次 |
| 最近记录: |