play.data.Form理解Java play框架中的子类化

时间:2014-02-06 06:34:46

标签: java json forms playframework spring-bean

我想使用Play!Framework的play.data.Form功能,但我遇到以下类的问题。 有人可以告诉我是否有办法让表单知道具有这种继承结构的嵌套路径? 到目前为止,我所尝试的是让它与Json一起工作。这是我的代码的摘要。

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ContactParam implements IEntityParam<Contact> {

    private Long id;

    private String name;

    private List<ContactFieldParam> contacts;

    private Long companyId;

    //standard getters and setters
}

详细信息定义如下:

@JsonSubTypes({
        @Type(EmailFieldParam.class),
        @Type(PhoneFieldParam.class),
        @Type(SocialNetworkFieldParam.class),
        @Type(AddressFieldParam.class),
        @Type(WebsiteUrlFieldParam.class)
})
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ctype")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public abstract class ContactFieldParam implements IEntityParam<ContactField> {

    private Long id;

    //standard getters and setters
}

当然所有子类都已实现(具有完全不同的字段集)并且具有可用的公共默认构造函数。我已经用Json(Jackson本身以及在play框架中包装的Json实现)测试了这个结构,并且它可以工作。问题是当我尝试通过声明Form<ContactParam>

在我的控制器中使用它时
private static final Form<ContactParam> contactForm = Form.form(ContactParam.class);

public static Result myAction() {
     Form<ContactParam> form = contactForm.bindFromRequest();
     if(form.hasErrors){
     //...
     }else{
     //...
     }
}

绑定将给我一个由InstanciationException引起的错误,因为它试图使用newInstance() Class<ContactFieldParam>方法直接实例化抽象类。我决定通过研究Form类(DataBinderBeanWrapperImpl)使用的springframework代码。

org.springframework.beans.InvalidPropertyException: Invalid property 'contacts[0]' of bean class [crud.params.contact.ContactParam]: Illegal attempt to get property 'contacts' threw exception; nested exception is org.springframework.beans.NullValueInNestedPathException: Invalid property 'contacts' of bean class [crud.params.contact.ContactParam]: Could not instantiate property type [crud.params.contact.fields.ContactFieldParam] to auto-grow nested property path: java.lang.InstantiationException
[...]
Caused by: org.springframework.beans.NullValueInNestedPathException: Invalid property 'contacts' of bean class [crud.params.contact.ContactParam]: Could not instantiate property type [crud.params.contact.fields.ContactFieldParam] to auto-grow nested property path: java.lang.InstantiationException
    at org.springframework.beans.BeanWrapperImpl.newValue(BeanWrapperImpl.java:633)

0 个答案:

没有答案