I have a simple bean, i.e.:
public class MyBean {
private boolean selected;
private String someString;
...
}
如果
selected
为真,我希望someString
是@NotNull
等等。有什么提示、链接可以实现这种行为吗?
谢谢 Jonny
I have a simple bean, i.e.:
public class MyBean {
private boolean selected;
private String someString;
...
}
selected
为真,我希望someString
是@NotNull
等等。@SpELAssert(value = "someString != null", applyIf = "selected",
message = "{validator.missing_some_string}")
public class MyBean {
private boolean selected;
private String someString;
...
}
实际上这太容易了。尝试一些更有趣的东西,比如当其中一个密码字段不为空时的相等性。
@SpELAssert(value = "password.equals(passwordVerify)",
applyIf = "password || passwordVerify",
message = "{validator.passwords_not_same}")
public class User {
private String password;
private String passwordVerify;
}
你甚至可以在这些表达式中使用自己的“辅助方法”!
与Hibernate Validator的@ScriptAssert
注释相比,这是纯Java解决方案,它不使用任何JSR-223兼容的脚本语言,这可能会有点棘手。另一方面,这个解决方案只对基于Spring的应用程序有趣。
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;
}
}