如果@Constraint(通过= {}验证),则使用Hibernate验证程序来验证约束 [英] Hibernate validator to validate constraints if @Constraint(validated by = {})
问题描述
我有一个使用休眠验证器进行验证的Spring Web应用程序。我有位于不同项目中的约束注释。在我的春季项目中,我需要针对这些约束的验证器,因为我需要一些服务来执行验证。所以情况是:我不能将约束验证器放在@Constraint(validatedBy = MyConstraintValidator.class)中,因为验证器在另一个项目中,我无法添加依赖项,因为这会创建循环依赖项,而这不是我们的方式想要它。
我注意到javax.constraints没有指定验证器,只是@Constraint(validatedBy = {})。
但是休眠验证器仍然知道如何验证它们。
是否可以告诉我的休眠验证器如何验证约束,而无需在约束中指定constaint-validators?
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 {};
}
谢谢!
推荐答案
javax.validation.constraints
将验证器留给实现。 Hibernate为这些约束提供验证器,并在引导时注册它们。
The javax.validation.constraints
leaves the validators to the implementation. Hibernate provides validators to these constraints, and registers them when bootstrapping.
您可以通过XML设置验证器,而无需使用 @Constraint(validatedBy = {})
。但是,这通常用于添加/替换您自己提供的验证器。我不确定它会如何帮助您,因为您仍然需要引用约束验证器。
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.
使用XML约束定义的示例:
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>
请参阅:通过XML配置
即将推出的5.2版本提供其他方式,例如使用服务加载程序或实现 ConstraintDefinitionContributor
。请参阅:提供约束定义
The upcoming 5.2 release provides more ways such as using a service loader or implementing ConstraintDefinitionContributor
. See: Providing constraint definitions
这篇关于如果@Constraint(通过= {}验证),则使用Hibernate验证程序来验证约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!