在Spring中验证域模型

时间:2014-03-05 20:56:40

标签: java spring validation

我想找到方法如何确保创建域模型对象时,它的有效性符合所有业务规则,例如:

  • 客户拥有有效的联系地址
  • 地址包含所有必填字段
  • 等等

我有一个想法是为每个域对象模型拥有一个作为验证器类的类,并用于验证该实例是有效的。

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;

    }

优点:

  • 为我的所有域模型定义自己的验证规则
  • 验证我感兴趣的所有对象或具体字段
  • 获取错误验证消息,指出哪些字段无效(并在例外情况下将其用作描述)

缺点:

  • 为所有域模型定义自己的验证规则
  • 当我有很多对象(例如AccountType类的实例)时,我需要为所有对象创建新对象(资源消耗)

我确信没有必要重新发明轮子,所以我想问你是否有什么东西(图书馆,最佳实践等)可以用来解决这种情况。我用谷歌搜索,我的“合同设计”概念的红色原则,并在这里找到了一些相应的主题,但我仍然不确定如何解决它的最佳方法。

我想找到最简单的解决方案,这种解决方案占用最少的系统资源,易于使用,并且在确保域模型对象有效的意义上是健壮的。

2 个答案:

答案 0 :(得分:3)

  

Spring自动启用注释驱动的声明性验证   如果您的网站上存在JSR-303提供程序,例如Hibernate Validator   类路径。

看看这个:

http://spring.io/blog/2009/11/17/spring-3-type-conversion-and-validation/

答案 1 :(得分:1)

首先查看Bean Validation API中实现的Hibernate Validator