Hibernate validator to validate constraints if @Co

2019-07-01 20:54发布

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条回答
Anthone
2楼-- · 2019-07-01 21:19

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

查看更多
登录 后发表回答