将参数从验证传递到休眠验证器中的自定义验证器

时间:2019-06-25 17:48:35

标签: java bean-validation javax.validation

我正在尝试使用自定义验证器来验证bean。但是,验证器需要从调用validate的方法传递给它的信息。有办法吗?

我无法在initialize中传递它,因为在创建bean时它不可用。

要验证的Bean

class vehicle {
   @VehicleNameValidator
   String vehicleName;
}

注释

@Target({ElementType.FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = VehicleNameValidatorImpl.class)
@Documented
public @interface VehicleNameValidator {
    String message() default "Invalid vehicle Name";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

自定义验证器

public class VehicleNameValidatorImpl implements ConstraintValidator<VehicleNameValidator, String[]> {

    @Override
    public boolean isValid(String vehicleName, ConstraintValidatorContext constraintValidatorContext) {
        boolean isValid = logicmethod()//some logic here
        return isValid;
    }
}

主要方法

public static void main(String[] args) {
   String whatIwantToPass = runtimelogic(args);
   vehicle veh1 = new vehicle();
   Set<ConstraintViolation<vehicle>> constraintViolations = 
   validator.validate(veh1);
}

如何将变量“ whatIwantToPass”从主方法传递给VehicleNameValidatorImpl。

2 个答案:

答案 0 :(得分:0)

ConstraintValidator的实现中,您始终可以使用@Autowired或@Value批注。我相信您可以在VehicleNameValidatorImpl.class

中使用类似的方法
    public class VehicleNameValidatorImpl implements ConstraintValidator<VehicleNameValidator, String[]> {

        @Autowired
        LogicWrittenClass logicWrittenClass;

        @Override
        public boolean isValid(String[] roles, ConstraintValidatorContext constraintValidatorContext) {
            String whatIwantToPass  = logicWrittenClass.runtimelogic();
            boolean isValid = logicmethod()//some logic here
            return isValid;
        }
    }

但是请确保使用spring来创建验证器bean,否则,使用valdiation工厂(Hibernate Validator作为参考实现)手动创建验证器bean时,bean注入不会起作用,不会将依赖项注入ConstraintValidator实例中。

答案 1 :(得分:0)

如果使用的是Hibernate Validator,则可能需要查看约束验证器的有效负载。在您的情况下,它看起来像这样:

在验证器中,您可以访问有效负载:

public boolean isValid(String vehicleName, ConstraintValidatorContext constraintValidatorContext) {
    boolean isValid = false;
    if ( constraintValidatorContext instanceof HibernateConstraintValidatorContext ) {
        final String payload = constraintValidatorContext
                .unwrap( HibernateConstraintValidatorContext.class )
                .getConstraintValidatorPayload( String.class );
        // do whatever you need
        isValid = logicmethod()//some logic here
    }
    return isValid;
}

可以在验证器工厂级别或每个验证器上设置有效负载,如下所示:

ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
        .configure()
        .buildValidatorFactory();

String whatIwantToPass = runtimelogic( args );

Validator validator = validatorFactory.unwrap( HibernateValidatorFactory.class )
        .usingContext()
        .constraintValidatorPayload( whatIwantToPass )
        .getValidator();

// use the validator with the constraint validator payload 
vehicle veh1 = new vehicle();
Set<ConstraintViolation<vehicle>> constraintViolations = validator.validate( veh1 );

有关更多详细信息,请参阅文档的此部分-Passing a payload to the constraint validator