亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring 5 不可變形式在沒有參數構造函數時也使用全參數構造函數

Spring 5 不可變形式在沒有參數構造函數時也使用全參數構造函數

米琪卡哇伊 2023-05-24 16:12:31
在一個不可變的類/對象中,我有一個沒有參數的構造函數將值初始化為默認值/null,另一個必需的參數構造函數將所有值初始化為構造函數的參數。使用表單綁定時(通過在控制器中的請求參數中指定),spring 始終調用無參數構造函數而不初始化值。我怎樣才能確保 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 String getName() {        return name;    }}還有我的控制器:@Controllerpublic class MyController {    @GetMapping("myStuff")    public String getMyStuff(ImmutableObj requestParams) {        // here the value of request params        // has nulls due to no arg constructor being called         return "someStuff";    }}調用“/myStuff?id=123&name=hello”時預期的 -requestParams.getId()=123, requestParams.getName()=hello實際的 -requestParams.getId()=null, requestParams.getName()=null
查看完整描述

1 回答

?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

Spring 總是調用無參數構造函數而不是初始化值。

當 Spring 發現該類有多個構造函數時,它會去尋找一個無參數的構造函數。如果 Spring 沒有找到它,它將拋出異常。

當 Spring 發現該類只有一個構造函數時,它會接受它,而不管它有多少個參數。

我怎樣才能確保 spring 只調用所需的參數構造函數?

唯一的方法是在類中只有一個構造函數。使它在 Spring 中明確無誤。

作為旁注,

  1. @ConstructorProperies({"id", "name"})如果字段名稱對應于 URL 參數名稱,則不需要。Spring 可以解決這個問題。

  2. public ImmutableObj() { 
       this(null, null);
    }

這不是一個好主意。ImmutableObj.empty()會更好。

作為獎勵,如果你想看看幕后發生了什么,這是我正在談論的片段

if (ctor == null) {

  Constructor<?>[] ctors = clazz.getConstructors();

  if (ctors.length == 1) {

    ctor = ctors[0];

  } else {

    try {

      ctor = clazz.getDeclaredConstructor();

    } catch (NoSuchMethodException var10) {

      throw new IllegalStateException("No primary or default constructor found for " + clazz, var10);

    }

  }

}


查看完整回答
反對 回復 2023-05-24
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號