将 trim 方法添加到 Lombok 中的 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;
我想在 setter 中添加 trim 方法,以便在长度中不计算白色 space。
public void setPassword(String password) {
this.password = password.trim();
}
如何在 Lombok setter 中添加 trim 方法?或者我必须写自定义 setter?
在这种情况下,您必须编写自定义 setter。如果你使用的是不可变的等价物(Wither),你可以将 trim() 放在构造函数中,然后再添加 @Wither to the method, and this would also hold for builders generated via @Builder 。这是一种更安全的方法,可确保密码始终为 trimmed.
@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();
}
我使用 Project Lombok 为字符串字段生成 getter/setter。此字段(例如密码)具有验证注释。
@Size(min = 6,max = 100, message = "The password must be between 6 and 100 characters")
private String password;
我想在 setter 中添加 trim 方法,以便在长度中不计算白色 space。
public void setPassword(String password) {
this.password = password.trim();
}
如何在 Lombok setter 中添加 trim 方法?或者我必须写自定义 setter?
在这种情况下,您必须编写自定义 setter。如果你使用的是不可变的等价物(Wither),你可以将 trim() 放在构造函数中,然后再添加 @Wither to the method, and this would also hold for builders generated via @Builder 。这是一种更安全的方法,可确保密码始终为 trimmed.
@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();
}