在以下情况下,如何覆盖电子邮件中对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中,并将其留在被覆盖的字段中,但我仍然收到来自超类的关于它为空的消息。有没有更懒惰的方法呢?
发布于 2011-08-19 03:12:36
由于约束是通过继承聚合的,因此最好的解决方案可能是将继承层次结构更改为如下所示:
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;
}https://stackoverflow.com/questions/7112626
复制相似问题