在以下情况下,如何在AuthorizedUser的电子邮件中覆盖验证:
public class Account {
@Length(min = 1, max = 100,
message = "'Email' must be between 1 and 100 characters in length.")
@NotNull(message = "'Email' must not be empty.")
protected String email;
@Length(min = 1, max = 50,
message = "'Name' must be between 1 and 50 characters in length.")
private String name;
}
public class AuthorizedUser extends Account {
@Length(min = 1, max = 40,
message = "'Field' must be between 1 and 50 characters in length.")
private String field;
}
我知道我可以通过执行以下操作覆盖AuthorizedUser上的setter中的电子邮件地址来“破解”解决方案:
@Override
public void setEmail(String email) {
this.email = email;
super.setEmail(" ");
}
感觉很脏......如果不编写自定义验证器,是否可以覆盖它?
我尝试将@Valid移动到超类中的setter,并将其保留在重写字段中,但我仍然收到来自超类的关于它为空的消息。是否有更懒惰的方法来做到这一点?
答案 0 :(得分:3)
由于约束是通过继承聚合的,因此最好的解决方案可能是将继承层次结构更改为以下内容:
public class BasicAccount {
protected String email;
@Length(min = 1, max = 50,
message = "'Name' must be between 1 and 50 characters in length.")
private String name;
}
public class EmailValidatedAccount extends BasicAccount {
@Length(min = 1, max = 100,
message = "'Email' must be between 1 and 100 characters in length.")
@NotNull(message = "'Email' must not be empty.")
@Override
public String getEmail() {
return email;
}
}
public class AuthorizedUser extends BasicAccount {
@Length(min = 1, max = 40,
message = "'Field' must be between 1 and 50 characters in length.")
private String field;
}