java Sping Boot 多值自定义约束验证器

b4lqfgs4  于 2023-06-04  发布在  Java
关注(0)|答案(2)|浏览(152)

我想为我的自定义约束验证器添加2个值,因为我有2个功能标志:

@JsonProperty(value = "name")
    @BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.AAA, values = {"aaa", "bbb"})
    @BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.BBB, values = {"ccc", "ddd"})
    private String parameter;

其中:

@Constraint(validatedBy = {BlockedWithoutEnabledFeatureFlagValidator.class})
@Target({FIELD, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface BlockedWithoutEnabledFeatureFlag {

    String message() default "{validation.constraints.BlockedWithoutEnabledFeatureFlag.message}";

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

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

    FeatureFlag feature();

    String[] values() default {};
}

和实施:

public class BlockedWithoutEnabledFeatureFlagValidator implements ConstraintValidator<BlockedWithoutEnabledFeatureFlag, Object> {
    private final FeatureFlagService featureFlagService;

    private List<String> blocked;
    private FeatureFlag feature;

    @Override
    public void initialize(BlockedWithoutEnabledFeatureFlag constraintAnnotation) {
        blocked = Arrays.asList(constraintAnnotation.values());
        feature = constraintAnnotation.feature();
    }

@Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

但现在我得到编译错误“重复注解”。如何做到这一点?

jvidinwx

jvidinwx1#

您应该使BlockedWithoutEnabledFeatureFlag可重复。要执行此操作:
1.创建新的“顶级”注解:

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

1.将@Repeatable添加到BlockedWithoutEnabledFeatureFlag注解

...
@Repeatable(RepeatableBlockedWithoutEnabledFeatureFlag.class)
public @interface BlockedWithoutEnabledFeatureFlag {
...

然后您应该能够添加多个@BlockedWithoutEnabledFeatureFlag注解。

6rvt4ljy

6rvt4ljy2#

你可以让你的验证器接受一个特征标志数组。

@Constraint(validatedBy = {BlockedWithoutEnabledFeatureFlagValidator.class})
    @Target({FIELD, PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @ReportAsSingleViolation
    public @interface BlockedWithoutEnabledFeatureFlag {
    
        String message() default "{validation.constraints.BlockedWithoutEnabledFeatureFlag.message}";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    
        FeatureFlag[] feature(); // <------ change here
    
        String[] values() default {};

}

这样做将允许您以两种方式使用它:

@BlockedWithoutEnabledFeatureFlag(feature = {FeatureFlag.AAA, FeatureFlag.BBB}, values = {"aaa", "bbb"})
    private String parameter;

    @BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.AAA, values = {"aaa", "bbb"})
    private String parameter2;

相关问题