Feel free to share your solution or ideas! This is how I solved this problem.
I used the idea from the link in my question, but in much easier way.
First, I solved a problem how to pass a Spring component or service into validator. I used a component which holds a static reference to the service.
Second, I validated the whole object as described in the link.
Here is the code!
1) Create annotation @PersonConstraint
and put in on Person
class.
This may help https://www.baeldung.com/javax-validation-method-constraints
@Target({ TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PersonValidator.class)
public @interface PersonConstraint {
String message() default "Specialization is not valid";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
CaseMode value();
}
2) Component which holds static reference to the service.
@Component // Spring component.
class ServiceHolderComponent {
private static SpecializationService SPECIALIZATION_SERVICE;
@Autowired
public ServiceHolderComponent(final SpecializationService specializationService) {
GROUP_SERVICE = Validate.notNull(groupService); //apache lib
}
public static SpecializationService getSpecializationService() {
return SPECIALIZATION_SERVICE;
}
}
3) And person validator
public class PersonValidator implements ConstraintValidator<PersonConstraint, Person> {
private final SpecializationService specializationService;
public UserDynamicEnumValidator() {
this(ServiceHolderComponent.getSpecializationService());
}
public UserDynamicEnumValidator(final SpecializationService specializationService) {
this.specializationService = specializationService;
}
@Override
public boolean isValid(final Person person, final ConstraintValidatorContext context) {
final Long groupId = person.getGroupId();
if (groupId == null) {
return true; // We consider it valid.
}
final String specialization = person.getSpecializat();
if (StringUtils.isEmpty(specialization)) {
return true; // We consider it valid.
}
// I changed the code of the service, so it returns a set of strings - projection query and collectors to set.
final Set<String> availableSpecializationValuesByGroup = specializationService.findByValue(groupId);
if (!availableSpecializationValuesByGroup.contains(specialization)) {
// To display custom message
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("Specialization is not valid").addConstraintViolation();
return false;
}
return true;
}
}
To display a custom message in validator check this