向Lombok中的setter添加trim方法



我使用Project Lombok生成String字段的getter/setter。这个字段,例如password,有验证注释。

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

我想在setter中添加trim方法,以便不计算长度中的空白。

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

如何在Lombok setter中添加trim方法?还是必须写自定义setter?

在这种情况下,您必须编写一个自定义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中作为实验性特性引入的。在lombok v1.18.10中,@Wither被重命名为@With,并从实验中移到核心包中。

从上面的链接到Wither。

最新更新