如何在 bean 验证上下文中设置默认组

How to set default group in bean validation context

我正在使用 bean 验证,我正在寻找一种可能性来设置我自己的 bean 验证注释的默认组。

我有这样的东西(工作):

Application.class(在 MyBean 上调用验证)

public class Application {
    public static void main(String[] args) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<MyBean>> violations =
            validator.validate(new MyBean(), SecondStep.class);
    }
}

MyBean.class(bean 本身;这是我要防止的)

public class MyBean {
    // I don't want to write this "groups" attribute every time, because it's very clear,
    // that this should only be validated for the second step, isn't it?
    @RequiredBySecondStep(groups=SecondStep.class)
    private Object myField;
}

RequiredBySecondStep.class(bean验证注解)

@Documented
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = RequiredBySecondStepValidator.class)
public @interface RequiredBySecondStep {
    String message() default "may not be null on the second step";
    Class<?>[] groups() default {};   // <-- here I want to set SecondStep.class
    Class<? extends Payload>[] payload() default {};
}

RequiredBySecondStepValidator.class(已实现的约束验证器)

public class RequiredBySecondStepValidator implements ConstraintValidator<RequiredBySecondStep, Object> {
    public void initialize(RequiredBySecondStep constraintAnnotation) {
    }

    public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {
        return object != null;
    }
}

SecondStep.class(bean验证组)

public interface SecondStep {
}

不幸的是,根据规范,无法像这样在 RequiredBySecondStep 注释中设置默认组:

Class<?>[] groups() default SecondStep.class;
// and using just the following in the bean:
@RequiredBySecondStep
private Object myField;

这将导致 RuntimeException:

javax.validation.ConstraintDefinitionException: Default value for groups() must be an empty array

此外,不仅有SecondStep。我想直接用 @RequiredByFirstStep@RequiredByFifthStep.

注释可能有 5 个不同的组

有什么好的实现方法吗?

我觉得你有点误会了。确实有办法做你想做的事,那是因为约束方面及其通过 ConstraintValidator 的验证与组和组序列正交。根据设计,约束(注释及其验证器)应该独立于要验证的组。即使你能让它工作,它也不是可移植的约束。就个人而言,我会重新考虑你想要实现的目标。 @RequiredByFirstStep 没有告诉你要求是什么。您应该开发约束来暗示它们正在验证什么(字符串长度,不为空等),何时或更好地执行它们的条件是由组接口控制的。