如何在Groovy中强制执行bean合同验证?

时间:2014-09-22 14:35:19

标签: validation groovy

我有一个包含两个字段的POGO:

class BaseEntity {
    Long id
    Long version
}

两个字段必须为正(既不是0也不是负)。 为防止使用非正ID /版本值创建(或设置)BaseEntity个实例,我需要添加的最少量代码是什么?

知道我可以完成这个旧的,Java方式":

class BaseEntity {
    private Long id
    private Long version

    BaseEntity(Long id, Long version) {
        super()

        setId(id)
        setVersion(version)
    }

    Long getId() {
        // Return a "clone" to preserve the original ID
        new Long(id)
    }

    Long getVersion() {
        // Return a "clone" to preserve the original version
        new Long(version)
    }

    def setId(Long id) {
        if(id < 1) {
            throw new IllegalArgumentException("ID must be positive!")
        }

        this.id = id
    }

    def setVersion(Long version) {
        if(version < 1) {
            throw new IllegalArgumentException("Version must be positive!")
        }

        this.version = version
    }
}

...但这看起来好像很多的样板代码,Groovy社区必须找到了一个快捷方式......


更新

我根据建议添加了GContracts,然后运行以下JUnit测试:

@Test
void id_cannotBeZero() {
    BaseEntity entity = new BaseEntity()

    entity.id = 0
}

当我运行它时,JUnit传递而不会抛出任何类型的异常。

1 个答案:

答案 0 :(得分:2)

使用下面的GContracts

@Grab(group='org.gcontracts', module='gcontracts-core', version='[1.2.12,)')
import org.gcontracts.annotations.*

@Invariant({ id > 0 && version > 0 })
class BaseEntity {
    Long id
    Long version
}