0

我们在 Grails 2.4.3 应用程序(从 2.3.8 迁移)中有一个这样的类:

@Validateable
class Foo {
    Integer noDefault;
    Integer withDefault = 1;

    static constraints = {
        noDefault(nullable:false)
        withDefault(nullable:false)
    }
}

此类正在使用这样的 Map 在复杂的配置机制中实例化:

[
    noDefault: 0,
    withDefault: 2
]

(实际上 Map 是一个巨大的 Map 的一部分,但类构造函数看到这个小的。)以前,如果我们从配置映射中省略 withDefault 条目,使用不为 null 的默认值,则该类可以工作。然而,在 Grails 2.4.3 中,它告诉我这个字段不能为空。我可以通过让它在约束中为空来修复它,但它允许将显式值设置为空(并覆盖默认值),这会在操作期间导致问题。

您是否知道一些解决方法,它保留了语义和正确的操作?

提前感谢,最好的问候:Balázs

4

1 回答 1

0

您所描述的与我所期望的不一致,也与我所看到的行为不一致。https://github.com/jeffbrown/validatedefaults上的项目包含以下代码。

https://github.com/jeffbrown/validatedefaults/blob/master/src/groovy/demo/Foo.groovy

// src/groovy/demo/Foo.groovy
package demo

import grails.validation.Validateable

@Validateable
class Foo {
    Integer noDefault;
    Integer withDefault = 1;

    static constraints = {
        noDefault(nullable:false)
        withDefault(nullable:false)
    }
}

https://github.com/jeffbrown/validatedefaults/blob/master/test/unit/demo/FooSpec.groovy的测试通过:

// test/unit/demo/FooSpec.groovy
package demo

import spock.lang.Specification
import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin

@TestMixin(GrailsUnitTestMixin)
class FooSpec extends Specification {

    void 'test validating default values'() {
        given:
        def map = [noDefault: 0]
        def foo = new Foo(map)

        expect:
        foo.validate()
    }
}

当我运行该应用程序时,我会得到相同的行为。

// grails-app/conf/BootStrap.groovy
import demo.Foo

class BootStrap {

    def init = { servletContext ->
        def map = [noDefault: 0]
        def foo = new Foo(map)

        // this prints true...
        println "Foo is valid? : ${foo.validate()}"
    }
    def destroy = {
    }
}

我希望这会有所帮助。

于 2014-09-19T16:58:12.723 回答