没有为Custom Java Bean Validator的约束找到验证器

时间:2016-12-22 22:32:38

标签: java validation bean-validation customvalidator custom-validators

我使用以下说明创建了一个新的自定义验证程序: https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-validator

public class CustomizableTypeValidator implements ConstraintValidator<CustomValidate, CustomValidator> {
    @Override
    public void initialize(final CustomValidate customValidate) {
    }

    @Override
    public boolean isValid(final CustomValidator customValidator, final ConstraintValidatorContext constraintValidatorContext) {
        if ( customValidator == null ) {
            return true;
        }

        return customValidator.isValid(constraintValidatorContext);
    }
}

但得到:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'com.amazon.mft.data.api.v1.CustomValidate' validating type 'com.amazon.mft.data.api.v1.CustomValidator'. Check configuration for 'transactionEntries[0].record.attributesObj'

我正在使用以下方法创建验证器:

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();

并称之为:

 validator.validate(obj)

我需要做什么才能将自定义验证器添加到它正在执行的其他验证中。我正在使用Hibernate Validator 5.2.4。

1 个答案:

答案 0 :(得分:0)

回答我自己的问题:  添加AutoService注释会修复它:

import com.google.auto.service.AutoService;

@AutoService(ConstraintValidator.class)
public class CustomizableTypeValidator implements ConstraintValidator<CustomValidate, CustomValidator> {
    @Override
    public void initialize(final CustomValidate customValidate) {
    }

    @Override
    public boolean isValid(final CustomValidator customValidator, final ConstraintValidatorContext constraintValidatorContext) {
        if ( customValidator == null ) {
            return true;
        }

        return customValidator.isValid(constraintValidatorContext);
    }
}