我正在尝试使用自定义验证器验证 bean。但是验证器需要从调用 validate 的方法传递给它的信息。有没有办法做到这一点?
我无法在初始化中传递它,因为它在创建 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。