我注意到,所有内置约束的 @Constraint
中的 validatedBy
参数的值均为空。即 @Constraint(validatedBy = {})
首先,为什么允许它们的 validatedBy
具有空值?我认为您可以仅将不需要额外验证的约束组合留空?
另外,请注意,尽管 validatedBy 为空,Hibernate 验证器仍然可以为每个内置约束找到验证器实现类,但如果我将约束的validatedBy 留空,我的自定义验证器永远不会得到已接。这是为什么?
谢谢。
I noticed that all built-in constraints have an empty value for the validatedBy
parameter in @Constraint
. i.e. @Constraint(validatedBy = {})
First, why are they allowed to have an empty value for validatedBy
? I thought you can leave it blank only for constraint composition that does not need addtional validation?
Also, note that the Hibernate Validator can still find a validator implementation class for each built-in constraint, despite the validatedBy
is empty, but if I leave the validatedBy blank for my constraint, my custom validator never gets picked up. Why is that?
Thanks.
发布评论
评论(3)
这些内置函数以特殊的特定于实现的方式进行处理,并且它们的验证器以编程方式配置。
对于 Hibernate Validator,它是在
ConstraintHelper.java
。我认为对于您的自定义约束,您无法实现相同的目标。Those built-in are treated in special implementation-specific way and their validators are configured programmatically.
For Hibernate Validator it's done in
ConstraintHelper.java
. I think you can't achieve the same for your custom constraints.也许看看这个答案:
如何由于 @Constraint validBy? 避免层之间的交叉依赖?
这两个链接:
以编程方式添加约束:
http: //docs.jboss.org/hibernate/stable/validator/reference/en-US/html/validator-specifics.html#section-programmatic-api
添加每个 xml 的约束:
http://docs.jboss。 org/hibernate/validator/4.1/reference/en-US/html/validator-xmlconfiguration.html
Maybe have a look at this answer:
How to avoid cross dependency between layers because of @Constraint validatedBy?
And those two links:
Adding constraints programmatically:
http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/validator-specifics.html#section-programmatic-api
Adding constraints per xml:
http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-xmlconfiguration.html
现在有几种方法 将接口与约束定义和验证器解耦,这样您就可以将它们放在不同的层中并将 validatedBy 属性留空。最简单的方法之一是使用 Hibernate ServiceLoader 在资源文件夹中的
/META-INF/services/javax.validation.ConstraintValidator
文件中添加验证器类(在 Hibernate 7 中更改为jakarta.validation.ConstraintValidator
)。Nowadays there are several methods to decouple the interface with the constraint definition and the validator, so you can have them in different layers and leave the validatedBy attribute empty. One of the simplest is using Hibernate ServiceLoader adding the validator classes in a
/META-INF/services/javax.validation.ConstraintValidator
file in resources folder (changed tojakarta.validation.ConstraintValidator
with Hibernate 7).