java – 跨字段验证(JSR 303)问题
作者:互联网
我有一个简单的豆,即:
public class MyBean {
private boolean selected;
private String someString;
...
}
因此,如果selected为true,我希望someString为@NotNull等.
任何提示,链接如何实现这种行为?
谢谢
强尼
解决方法:
您可以通过使用自定义验证器注释MyBean来执行此操作,例如:
@ValidMyBean
public class MyBean {
private boolean selected;
private String someString;
...
}
ValidMyBean:
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyBeanValidator.class)
public @interface ValidMyBean {
boolean allViolationMessages() default true;
Class<?>[] constraints() default {};
Class<?>[] groups() default {};
String message() default "{ValidMyBean.message}";
Class<? extends Payload>[] payload() default {};
}
MyBeanValidator:
public final class MyBeanValidator implements
ConstraintValidator<ValidMyBean, MyBean> {
@Override
public void initialize(
@SuppressWarnings("unused") final ValidMyBean constraintAnnotation) {
}
@Override
public boolean isValid(final MyBean value,
final ConstraintValidatorContext context) {
boolean isValid = true;
//your validation here
return isValid;
}
}
标签:java,bean-validation 来源: https://codeday.me/bug/20190903/1795326.html