簡體   English   中英

在 Lombok 中將 trim 方法添加到 setter

[英]Add trim method to setter in Lombok

我使用 Project Lombok 為字符串字段生成 getter/setter。 此字段(例如密碼)具有驗證注釋。

@Size(min = 6,max = 100, message = "The password must be between 6 and 100 characters") 
private String password;

我想在設置器中添加修剪方法,以便不計算長度中的空白。

public void setPassword(String password) {
    this.password = password.trim();
}

如何在 Lombok setter 中添加修剪方法? 或者我必須編寫自定義設置器?

在這種情況下,您必須編寫自定義設置器。 如果您使用的是不可變等效項(Wither),則可以將 trim() 放在構造函數中,然后將@Wither添加到方法中,這也適用於通過@Builder生成的構建器。 這是一種更安全的方法,可確保始終修剪密碼。

  @Wither
  @Size(min = 6,max = 100, message = "The password must be between 6 and 100 characters") 
  private final String password; //guaranteed to be trimmed


  public MyClass(final String password){  
    this.password=  password.trim();
  }

更新:

@Wither 在 lombok v0.11.4 中作為實驗性功能引入。 @Wither 已重命名為 @With,並在 lombok v1.18.10 中退出實驗性並進入核心包。

從 aboce 鏈接到 Wither。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM