我想找到方法如何确保创建域模型对象时,它的有效性符合所有业务规则,例如:
我有一个想法是为每个域对象模型拥有一个作为验证器类的类,并用于验证该实例是有效的。
public interface IValidator {
public boolean isValid();
}
AccountType域模型类的接口实现的简化说明:
public final class AccountTypeValidator implements IValidator {
private final AccountType accountType;
public AccountTypeValidator(final AccountType accountType) {
this.accountType = accountType;
}
public boolean isValidName() {
if (StringUtils.isBlank(accountType.getName()) == true) {
return false;
}
return true;
}
public final boolean isValid() {
if (isValidName() == false) {
return false;
}
return true;
}
}
当我在我的应用程序中使用此验证类时,我可以执行类似的操作:
public void setAccountType(final AccountType accountType) {
AccountTypeValidator validator = new AccountTypeValidator(accountType);
if (validator.isValid() == false) {
throw new IllegalArgumentException("....");
}
this.accountType = accountType;
}
优点:
缺点:
我确信没有必要重新发明轮子,所以我想问你是否有什么东西(图书馆,最佳实践等)可以用来解决这种情况。我用谷歌搜索,我的“合同设计”概念的红色原则,并在这里找到了一些相应的主题,但我仍然不确定如何解决它的最佳方法。
我想找到最简单的解决方案,这种解决方案占用最少的系统资源,易于使用,并且在确保域模型对象有效的意义上是健壮的。
答案 0 :(得分:3)
Spring自动启用注释驱动的声明性验证 如果您的网站上存在JSR-303提供程序,例如Hibernate Validator 类路径。
看看这个:
http://spring.io/blog/2009/11/17/spring-3-type-conversion-and-validation/
答案 1 :(得分:1)