gpt4 book ai didi

java - 在 hibernate validator 中将参数从验证传递到自定义 validator

转载 作者:行者123 更新时间:2023-12-02 09:44:37 25 4
gpt4 key购买 nike

我正在尝试使用自定义 validator 来验证 bean。但是 validator 需要从调用验证的方法传递给它的信息。有办法做到这一点吗?

我无法在初始化中传递它,因为它在创建 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 { };
}

自定义 validator

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。

最佳答案

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

在您的 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;
}

并且可以在 validator 工厂级别或每个 validator 级别设置有效负载,如下所示:

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

关于java - 在 hibernate validator 中将参数从验证传递到自定义 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56759514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com