有没有办法将验证注释与自定义验证器链接,除非通过@Constraint注释?
Unique.java
@Documented
//----@Constraint(validatedBy = { UniqueValidator.class })----//
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Unique {
String message() default "org.hibernate.validator.constraints.Unique.message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
UniqueValidator.java
public class UniqueValidator implements ConstraintValidator<Unique, Object> {
@Override
public void initialize(Unique unique) {}
@Override
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
}
}
答案 0 :(得分:2)
您始终需要@Constraint
注释。它是Bean Validation的标记,我们有一个约束注释。但是,您可以使用空的validatedBy
值:
@Documented
@Constraint(validatedBy = { })
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Unique {
String message() default "org.hibernate.validator.constraints.Unique.message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
如果您将validatedBy
留空,则有两种选择。如果您想坚持使用Bean Validation功能,可以通过约束映射文件(在validation.xml
中列出)
<constraint-mappings
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.1.xsd"
xmlns="http://jboss.org/xml/ns/javax/validation/mapping" version="1.1">
...
<constraint-definition annotation="com.acme.Unique">
<validated-by include-existing-validators="false">
<value>com.acme.UniqueValidator</value>
</validated-by>
</constraint-definition>
Hibernate Validator 5.2还提供了一个特定于提供程序的功能来添加约束定义。请查看ConstraintDefintionContributor
- http://docs.jboss.org/hibernate/validator/5.2/reference/en-US/html_single/#section-constraint-definition-contribution。您可以在引导程序中提供自己的贡献者,也可以使用Java ServiceLoader机制,只需添加META-INF/services/javax.validation.ConstraintValidator
列出ConstraintValidator
实现。