java - 在 Spring 中验证域模型

标签 java spring validation

我想找到一种方法来确保如果创建了域模型对象,它的含义是有效的,并且满足所有业务规则,例如:

  • 客户有有效的联系地址
  • 地址由所有必填字段组成
  • 等等

我有一个想法,为每个域对象模型拥有自己的类,该类充当 validator 类,并用于验证实例是否有效。

public interface IValidator {    
    public boolean isValid();    
}

AccountType 域模型类的接口(interface)实现的简化说明:

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 类的实例)时,我需要为所有对象创建新对象(资源消耗)

我确信没有必要重新发明轮子,所以我想问你是否有什么东西(库、最佳实践等)可以用来解决这种情况。我在谷歌上搜索了“按契约(Contract)设计”概念的原则,并在此处找到了一些相应的主题,但我仍然不确定解决它的最佳方法是什么。

我希望找到一种最简单、消耗最少系统资源、易于使用且功能强大的解决方案,以确保域模型对象有效。

最佳答案

Spring automatically enables annotation-driven declarative validation if a JSR-303 provider, such as Hibernate Validator, is present on your classpath.

看看这个:

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

关于java - 在 Spring 中验证域模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22209035/

相关文章:

java - Spring Boot 自定义运行状况指示器未显示

java - 在 Spring Boot 中通过 @Value 检索 application.properties 值

spring - QueryDsl - 如何使用 maven 创建 Q 类?

java - jsf(richfaces)只读输入文本验证

javascript - 如何在没有javascript的情况下验证html文件?

java - 每次调用方法时创建一个新的 Set

java.lang.OutOfMemoryError : PermGen space still exist 错误

javascript - 如何根据选择的选项值验证表单输入字段?

java - 骨架实现与普通抽象类有何不同?

java - 我不知道请帮忙...无法启动 Activity ComponentInfo{...} : java. lang.NullPointerException