第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

Spring 5 不可變形式在沒有參數(shù)構(gòu)造函數(shù)時也使用全參數(shù)構(gòu)造函數(shù)

Spring 5 不可變形式在沒有參數(shù)構(gòu)造函數(shù)時也使用全參數(shù)構(gòu)造函數(shù)

米琪卡哇伊 2023-05-24 16:12:31
在一個不可變的類/對象中,我有一個沒有參數(shù)的構(gòu)造函數(shù)將值初始化為默認值/null,另一個必需的參數(shù)構(gòu)造函數(shù)將所有值初始化為構(gòu)造函數(shù)的參數(shù)。使用表單綁定時(通過在控制器中的請求參數(shù)中指定),spring 始終調(diào)用無參數(shù)構(gòu)造函數(shù)而不初始化值。我怎樣才能確保 spring 只調(diào)用所需的參數(shù)構(gòu)造函數(shù)?這是在 spring 版本 5.1.5 中。我也嘗試在“必需的參數(shù)構(gòu)造函數(shù)”上添加 @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";    }}調(diào)用“/myStuff?id=123&name=hello”時預(yù)期的 -requestParams.getId()=123, requestParams.getName()=hello實際的 -requestParams.getId()=null, requestParams.getName()=null
查看完整描述

1 回答

?
HUH函數(shù)

TA貢獻1836條經(jīng)驗 獲得超4個贊

Spring 總是調(diào)用無參數(shù)構(gòu)造函數(shù)而不是初始化值。

當 Spring 發(fā)現(xiàn)該類有多個構(gòu)造函數(shù)時,它會去尋找一個無參數(shù)的構(gòu)造函數(shù)。如果 Spring 沒有找到它,它將拋出異常。

當 Spring 發(fā)現(xiàn)該類只有一個構(gòu)造函數(shù)時,它會接受它,而不管它有多少個參數(shù)。

我怎樣才能確保 spring 只調(diào)用所需的參數(shù)構(gòu)造函數(shù)?

唯一的方法是在類中只有一個構(gòu)造函數(shù)。使它在 Spring 中明確無誤。

作為旁注,

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

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

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

作為獎勵,如果你想看看幕后發(fā)生了什么,這是我正在談?wù)摰钠?/p>

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);

    }

  }

}


查看完整回答
反對 回復(fù) 2023-05-24
  • 1 回答
  • 0 關(guān)注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號