Hi guys,
I’m implement a custom corrrelation validator, just like this:
Correlation.java
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Constraint(validatedBy = CorrelationValidator.class)
public @interface Correlation {
String message() default "";
String ref() default "";
String refValue() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
User.java
public class User {
@Correlation(ref = "name", refValue = "alan", message = " when name is alan, the age can not be null")
private Integer age;
private Integer id;
private String name;
//getters and setters...
}
CorrelationValidator.java
public class CorrelationValidator implements ConstraintValidator<Correlation, String> {
@Override
public void initialize(Correlation constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
// I want to get the root bean instance User here and get the user.name to do a validation, but I can not obtain it from the constraintValidatorContext ;
return true;
}
}
I want to get the root bean instance User in the CorrelationValidator .isValue() method and get the user.name to do a validation, but I can not obtain it from the constraintValidatorContext ;
when I hava a look at your sources code ConstraintTree.java,I found I can obtain the root bean in ValidationContext.getRootBean(), I hope you can put executionContext into the isValue method.
ConstraintTree.java
private <T, V> Set<ConstraintViolation<T>> validateSingleConstraint(ValidationContext<T> executionContext,
ValueContext<?, ?> valueContext,
ConstraintValidatorContextImpl constraintValidatorContext,
ConstraintValidator<A, V> validator) {
boolean isValid;
try {
@SuppressWarnings("unchecked")
V validatedValue = (V) valueContext.getCurrentValidatedValue();
isValid = validator.isValid( validatedValue, constraintValidatorContext );
}
catch ( RuntimeException e ) {
throw log.getExceptionDuringIsValidCallException( e );
}
if ( !isValid ) {
//We do not add these violations yet, since we don't know how they are
//going to influence the final boolean evaluation
return executionContext.createConstraintViolations(
valueContext, constraintValidatorContext
);
}
return Collections.emptySet();
}
if you hava a better solution please notice me, I will appreciate it.