我创建了我的第一个自定义验证注释,其中 validator 类作为内部类(我发现它安排得很好)。 它看起来像这样:
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {OneOfGroupNotNull.Validator.class})
@Documented
public @interface OneOfGroupNotNull {
// custom annotation properties
String[] fields();
// required by JSR-303
String message() default "One of group must be not null. {fields}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
public class Validator implements ConstraintValidator<OneOfGroupNotNull, Object> {
private String[] fields;
@Override
public boolean isValid(Object bean, ConstraintValidatorContext cvc) {
int countNotNull = 0;
for (String field : fields) {
try {
String property = BeanUtils.getProperty(bean, field);
if (property != null) {
countNotNull++;
}
} catch (Exception ex) {
throw new RuntimeException("Validation for field " + field + " of type " + bean.getClass()+ " raised exception.", ex);
}
}
return countNotNull == 1;
}
@Override
public void initialize(OneOfGroupNotNull a) {
fields = a.fields();
}
}
}
使用此 validator 注释的 bean 类可能如下所示:
@OneOfGroupNotNull(fields = {"a", "b", "c"})
public interface MyBean {
String getA();
Rarity getB();
Boolean getC();
}
问题是我找不到格式化字符串数组“fields”的方法。它只需要 to string 方法,结果如下: 组之一必须不为空。 [Ljava.lang.String;@157d954
最佳答案
如果您将字段
的类型从String[]
更改为String
,则带有字段名称的消息将正确显示。要获取约束中的字段名称,只需用逗号 split()
即可。
另一个选项是在约束内生成自定义消息,如下所示:
cvc.disableDefaultConstraintViolation();
cvc.buildConstraintViolationWithTemplate("error message")
.addNode("field name with error")
.addConstraintViolation();
关于java - 将(字符串)数组格式化为 Bean 验证消息的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13344985/