是否可以验证bean,确保在不实现自定义验证器的情况下,三个字段中至少有一个不为空?
所以:
public class Foo {
@NotNull(groups = {AtLeastOne.class})
private Bar b1;
@NotNull(groups = {AtLeastOne.class})
private Bar b2;
@NotNull(groups = {AtLeastOne.class})
private Bar b3;
}
但没有这些群体意味着我想一次性验证它们。我希望b1或b2或b3不为空。
干杯,
答案 0 :(得分:1)
您需要注释@Validated
。例如:
public class Foo {
@NotNull(groups = {AtLeastOne.class})
private Bar b1;
@NotNull(groups = {AtLeastTwo.class})
private Bar b2;
@NotNull(groups = {AtLeastThree.class})
private Bar b3;
}
@Validated(value=AtLeastOne.class)
只会验证b1
@Validated(value=AtLeastTwo.class)
只会验证b2
<强>更新强>
@NotAllNull(value={"b1", "b2", "b3"})
public class Foo {
private Bar b1;
private Bar b2;
private Bar b3;
}
@Documented
@Constraint(validatedBy = NotAllNullValidator.class)
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface NotAllNull {
String[] value;
}
public class NotAllNullValidator implements ConstraintValidator<NotAllNull, Object> {
private String[] fields;
@Override
public void initialize(final NotAllNull constraintAnnotation) {
fields = constraintAnnotation.value();
}
@Override
public boolean isValid(final Object instance, final ConstraintValidatorContext context) {
boolean result = false;
for(int i = 0 ; i < fields.length; i++) {
result |= org.apache.commons.beanutils.BeanUtils.getProperty(instance, fields[i])!=null;
}
return result;
}
}
我这里没有IDE,代码中可能有一些错误,但希望你能看到代码背后的想法
答案 1 :(得分:0)
看一下你班上的@Valid和@Validated注释