java Spring绑定抽象对象
我对春季的表单数据绑定有问题
给定的对象具有以下结构:
- SiteContent
|-List<Panel> boxList
panel元素如下所示:
- Panel
|- Collection<AbstractPanelElement> panelElements
带有AbstractPanelElements
的集合是关键点,因为AbstractPanelElements
可能是Divider
、Address
或Icon
如果我提交的表单包含这些类型的多个元素,则会出现以下错误:
org.springframework.beans.InvalidPropertyException:
Invalid property 'boxList[0].panelElements[0]' of bean class [com.panel.SiteContent]:
Illegal attempt to get property 'panelElements' threw exception; nested exception is org.springframework.beans.NullValueInNestedPathException:
Invalid property 'boxList[0].panelElements' of bean class [com.panel.SiteContent]:
Could not instantiate property type [com.panel.AbstractPanelElement] to auto-grow nested property path: java.lang.InstantiationException
经过研究,我发现我们可以在控制器中设置以下(InitBinder):
@InitBinder
public void initBinder(WebDataBinder binder){
binder.setAutoGrowNestedPaths(false);
}
但这并不能解决问题,这是有道理的,我认为spring不能实例化一个抽象类
现在我的问题是,我是否有可能解决这个问题,还是没有办法
# 1 楼答案
您需要提供自己的绑定方法,然后创建正确的子类型。Spring不知道应该为哪个元素实例化哪些子类型
例如:
您也可以修改它来处理列表项。 在我的脑海中,我知道有一些PropertyEditor,可以实现从字符串表示到类的转换。但我现在研究的时间有限
这可能会帮助你: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-beans-conversion-customeditor-registration