1

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

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

Application.class(在 MyBean 上调用 validate)

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:groups() 的默认值必须是一个空数组

此外,不仅有第二步。可能有 5 个不同的组我想直接用@RequiredByFirstStep或注释@RequiredByFifthStep

有没有好的方法来实现这个?

4

1 回答 1

2

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

于 2015-08-22T19:05:10.183 回答