最近,我在自定义注释中添加了@Repeatable。一旦我向字段添加了重复注释,它就可以正常工作,但是具有单个注释的字段却无法正常工作。

例:

以下作品:

@NotNull
@CustomValidator(type = Type.SIZE, max = 80)
@CustomValidator(type = Type.FIELD)
private String firstName;


但是以下操作不起作用(因为它仅包含一个@CustomValidator):

@NotNull
@CustomValidator(type = Type.EMAIL)
private String email;



  CustomValidator.java


import java.lang.annotation.Repeatable;

import javax.validation.Constraint;
import javax.validation.Payload;

@Constraint(validatedBy = CustomValidatorImpl.class)
@Repeatable(RepeatableCustomValidator.class)
public @interface CustomValidator {

    String message() default "";

    int min() default 1;

    int max() default Integer.MAX_VALUE;

    String format() default "dd.MM.yyyy";

    String[] values() default {};

    Type type();

    boolean optional() default false;

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

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



  RepeatableCustomValidator.java


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatableCustomValidator {
    CustomValidator[] value();
}



  CustomValidatorImpl.java


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CustomValidatorImpl implements ConstraintValidator<CustomValidator, String> {
...............
@Override
public void initialize(CustomValidator constraintAnnotation) {
..........

}
    }


依存关系:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>


JAVA_VERSION =“ 1.8.0_121”

我有什么想念的吗?

最佳答案

正如@Holger指出的那样,

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)


将这两个添加到您的CustomValidator类可解决此问题。
顺便说一句,如果我们不提及这两个策略,也不应进行普通验证​​。
您确定没有这些就可以了吗?正如我尝试的那样,它不起作用。

10-01 04:53