我正在使用 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
。
有没有好的方法来实现这个?