5

I have a Spring webapplication that uses hibernate validator for validation. I have constraint annotations that are located in a different project. I need to have validators for these constraints in my spring project because I need some services to perform validation. So the situation is: I cannot place my constraint validators in @Constraint(validatedBy = MyConstraintValidator.class) because the validator is in a different project, I cannot add a dependency because that would create a cyclic dependency and it is just not the way we want it. I noticed that javax.constraints don't have validators specified, it's just @Constraint(validatedBy= {}). But hibernate validator still knows how to validate them. Is there a way to tell my hibernate validator how to validate my constraints without specifying constaint-validators in my constraints?

I hope be able to validate this constraint:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Constraint(validatedBy = {})
public @interface OneOf {

    String message() default "{OneOf}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Thanks!

1 Answer 1

4

The javax.validation.constraints leaves the validators to the implementation. Hibernate provides validators to these constraints, and registers them when bootstrapping.

You can set the validators via XML without using @Constraint(validatedBy = { }). However, this is usually used to add to/replace the provided validators with your own. I'm not sure how it will help you since you still need to reference the constraint validator.

Example of using XML constraint definition:

<constraint-definition annotation="org.mycompany.CheckCase">
    <validated-by include-existing-validators="false">
        <value>org.mycompany.CheckCaseValidator</value>
    </validated-by>
</constraint-definition>

See: Configuring via XML

The upcoming 5.2 release provides more ways such as using a service loader or implementing ConstraintDefinitionContributor. See: Providing constraint definitions

Sign up to request clarification or add additional context in comments.

2 Comments

The first Alpha of 5.2 is out now, it also provides support for custom ConstraintDefinitionContributors.
I'm gonna accept this although couldn't try it.. for some reason validation.xml gives parse exception.. and I have to use 4.3 version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.