Configuring custom validation with validator dependancy injection

I'm trying to define constraint definition with Hibernate Validation 6.0.1 where the validator is in a different location (.jar/project) relative to the constraint annotation. Aka, I have my objects that I want to validate that are in the project "api" with the annotation definition, but I'll have the validators in the project "modules/common"

I was following what was describes in the documentation.

Configuration file

@Bean
public Validator validator() {

    HibernateValidatorConfiguration configuration = Validation
            .byProvider( HibernateValidator.class )
            .configure();

    ConstraintMapping constraintMapping = configuration.createConstraintMapping();

    constraintMapping
            .constraintDefinition(ValidationComplexePerson.class)
                .validatedBy(ValidationComplexePersonValidator.class);

    return configuration.addMapping( constraintMapping )
            .buildValidatorFactory()
            .getValidator();

Constraint Annotation

@Documented
@Constraint(validatedBy = { })
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ValidationComplexePerson {
...}

Validator

public class ValidationComplexePersonValidator 
     implements ConstraintValidator<ValidationComplexePerson, Personne> {

@Override
public void initialize(ValidationComplexePerson constraintAnnotation) {
}

@Override public boolean isValid(
          Personne personne, 
          ConstraintValidatorContext constraintValidatorContext) {
    if (personne.nom.matches(".*\\d+.*")) {
        return false;
    }
    return true;
}

My problem The problem I have is that if I don't put the "@Constraint(validatedby={})" in the Annotation, I get the error

HV000116: The annotation type must be annotated with @javax.validation.Constraint when creating a constraint definition.

when reaching the ".constraintDefinition" in the Bean config.

On the other hand, if I put the "@Constraint(validatedby={})", I get

Error:(17, 1) java: For non-composed constraints a validator implementation must be specified using @Constraint#validatedBy().

Any suggestion on what could be worng or alternatives to this solution?

I also tried the procedure presented here.

Upvotes: 0

Views: 1194

Answers (1)

Guillaume Smet
Guillaume Smet

Reputation: 10529

I suspect you are using the annotation processor as your second error comes from it?

The issue is that the annotation processor check is not correct in this case. I think we should probably remove it as there's no way to make this check work with the programmatic API.

Just remove the annotation processor for now and it should work OK.

I opened https://hibernate.atlassian.net/browse/HV-1470 to track this issue.

Upvotes: 1

Related Questions