绑定动态列表时出现java问题
初始问题(更新如下)
我正在使用AutoPopulatingList
列表来建立一个对象,该对象使用一些参数调用构造函数。类似下面的代码。我以前用过它,没有任何问题,但我现在不能让它工作
public class Tree {
...
private List<Node> nodes = new AutoPopulatingList<Node>(new ElementFactory<Node>() {
@Override
public Node createElement(final int index) throws ElementInstantiationException {
//call custom controller
return new Node(index, ...other params);
}
});
...
//getters & setters
}
对象作为模型属性param(@ModelAttribute Tree
)映射到控制器中。因此,我以如下形式发送值:
nodes[0].field1 = some value
nodes[1].field2 = other value
但是当我发送这些参数时,spring无法实例化Node
对象,因为它正在为Node
对象寻找一个没有参数的构造函数,并且它会引发如下异常:
org.springframework.beans.NullValueInNestedPathException: Invalid property 'nodes' of bean class [...Node]: Could not instantiate property type [...Node] to auto-grow nested property path: java.lang.InstantiationException: ...Node.()
如果我向Node
类添加一个没有参数的构造函数,则不会出现错误,但是当我发送nodes[0]
时,它会被Node()
调用,而不是使用提供的ElementFactory
奇怪的是,如果我在控制器treeObject.getNodes().get(0)
中执行此操作,那么调用的构造函数就是带有params的构造函数(应该是这样的)
我正在使用Spring3.0.4。释放
有人知道为什么会这样吗?这会是一只虫子吗
谢谢
更新
我已经构建了一个类似于AutoPopulatingList的列表的自定义实现,以检查这是否是AutoPopulatingList的问题,但它会发生相同的行为。 实施只是覆盖:
public Node get(int index) {
//here just creates the object it it doesn't exist in the position
}
所以问题是为什么我在控制器中执行以下操作:
public String controllerMethod(
@ModelAttribute Tree tree, BindingResult result, Model model){
...
}
我发送节点[0]。因为在索引的0位置没有任何对象,所以它必须实例化该对象。但问题是,它是在调用树之前被Node()构造函数调用的。获取(0)。那么,为什么Spring调用默认构造函数呢?我怎样才能强迫它使用tree。获取(0)以实例该对象,而不是节点()
# 1 楼答案
我通过禁用活页夹中的AutologownestedPaths解决了这个问题,这样自动填充列表就可以在自己的工厂中自动增长