【发布时间】:2015-08-21 15:37:58
【问题描述】:
我正在处理 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 注释。
有没有好的方法来实现这个?
【问题讨论】:
标签: java bean-validation validationgroup