在一个不可变的类/对象中,我有一个无参数构造函数将值初始化为 default/null,另一个必需的参数构造函数将所有值初始化为来自构造函数的参数。
使用表单绑定时(通过在控制器中的请求参数中指定),spring 始终调用无参数构造函数而不初始化值。如何确保 spring 仅调用所需的参数构造函数?
这是春季版本 5.1.5。我也尝试在“必需参数构造函数”上添加@ConstructorProperties,但无济于事。
我的不可变表单/bean 对象:
public class ImmutableObj {
private final Integer id;
private final String name;
// no arg constructor
// spring calls this one when resolving request params
public ImmutableObj() {
this(null, null);
}
// required args constructor
// I want spring to call this one when resolving request params
@ConstructorProperies({"id", "name"})
public ImmutableObj(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public …
Run Code Online (Sandbox Code Playgroud)