我想使用 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 类(DataBinder
和BeanWrapperImpl
)使用的 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)