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

时间:2015-08-21 15:37:59

标签: java bean-validation validationgroup

我正在使用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()必须是一个空数组

此外,不仅有SecondStep。可能有5个不同的群组,我想直接使用@RequiredByFirstStep@RequiredByFifthStep进行注释。

有没有一种好方法可以实现这个?

1 个答案:

答案 0 :(得分:2)

我觉得你有点不对劲。确实有办法做你想做的事情,因为约束的方面和它们通过ConstraintValidator的验证与组和组序列是正交的。根据设计,约束(注释及其验证器)应独立于要验证的组。即使你能让它工作,它也不会是便携式约束。就个人而言,我会重新思考你想要实现的目标。 @RequiredByFirstStep并未告诉您需求是什么。您应该开发约束,这意味着它们正在变量(字符串长度,而不是空等),何时或更好地执行它们然后由组接口控制。