gpt4 book ai didi

java - 绑定(bind)动态列表时的奇怪问题

转载 作者:IT老高 更新时间:2023-10-28 13:53:59 25 4
gpt4 key购买 nike

初始问题(以下更新)

我正在使用 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
}

对象作为模型属性参数(@ModelAttribute Tree)映射到 Controller 中。所以我发送如下形式的值:

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

奇怪的是,如果我在 Controller treeObject.getNodes().get(0) 中执行此操作,则调用的构造函数是带有参数的构造函数(应该如此)。

我正在使用 Spring 3.0.4.RELEASE。

有人知道为什么会这样吗?这可能是一个错误吗?

谢谢。


更新

我已经构建了一个类似于 AutoPopulatingList 的 List 的自定义实现,以检查这是否是 AutoPopulatingList 的问题,但它会发生相同的行为。实现只是覆盖:

public Node get(int index) {
//here just creates the object it it doesn't exist in the position
}

所以问题是为什么当我在 Controller 中这样做时:

public String controllerMethod(
@ModelAttribute Tree tree, BindingResult result, Model model){
...
}

我发送 nodes[0].something 因为在 index 的位置 0 中没有任何对象,它必须实例化该对象。但问题是它在调用tree.get(0)之前调用了Node()构造函数。那么,为什么 Spring 会调用默认构造函数呢?如何强制它使用 tree.get(0) 而不是 Node() 来实例化对象?

最佳答案

我已经通过禁用 Binder 中的 autogrownestedpaths 解决了这个问题,因此这允许 Autopopulating list 将使用自己的工厂处理自动增长。

@InitBinder
public void initBinder(WebDataBinder binder){
binder.setAutoGrowNestedPaths(false);
}

关于java - 绑定(bind)动态列表时的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com