对于继承的字段,Spring Validation rejectValue

时间:2014-05-13 19:41:09

标签: spring spring-validator

我得到了例外

org.springframework.beans.NotReadablePropertyException: Invalid property 'entries[0].reason' of bean class [my.company.data.SDROrder]: Bean property 'entries[0].reason' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

来自以下代码段:

Errors errors = new BeanPropertyBindingResult(new SDROrder(), "sdr");
orderValidator.validate(order, errors);
验证者

public class OrderValidator implements Validator
{

    @Override
    public boolean supports(Class<?> clazz)
    {
        return Order.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(final Object target, final Errors errors)
    {
        errors.rejectValue("entries[0].reason", "Wrong Reason");
    }

}

我们有这样的数据层次结构

public class Order
{
    private List<AbstractOrderEntry> entries;

    public List<AbstractOrderEntry> getEntries()
    {
        return entries;
    }

    public void setEntries(List<AbstractOrderEntry> entries)
    {
        this.entries = entries;
    }
}

public class SDROrder extends Order
{

}

public class AbstractOrderEntry
{

}


public class SDROrderEntry extends AbstractOrderEntry
{
    private String reason;

    public String getReason()
    {
        return reason;
    }

    public void setReason(String reason)
    {
        this.reason = reason;
    }
}

请在此处查看工作示例:here

更新1 :只是为了澄清。问题是我尝试在具有对象集合的对象上 rejectValue ,其中每个元素在运行时具有特定属性但在编译时没有。 Spring使用Bean的属性来解析这些字段,但无法找到继承的属性。问题是:我可以解释Spring以某种方式解决继承的字段吗?

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决方案。 诀窍在

  org.springframework.validation.Errors.pushNestedPath(String)

org.springframework.validation.Errors.popNestedPath()

方法

正确的验证应按如下方式进行:

    errors.pushNestedPath("entries[0]");
    errors.rejectValue("reason", "Wrong Reason");
    errors.popNestedPath();