Groovy 2.4.4 命令对象——重用验证器闭包

Groovy 2.4.4 command objects - reusing validator closure

假设我有以下命令:

@Validateable
class MyCommand {
    String cancel_url
    String redirect_url
    String success_url

    static constraints = {
        cancel_url nullable: false, validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
        redirect_url nullable: false, validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
        success_url nullable: false, validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
    }
}

假设我想对任何 URL 字段执行一些通用验证(例如,检查是否允许该域)。将此通用验证代码分解为单独的函数而不是在每个验证闭包中放置相同的块的语法是什么?

您是否尝试从多个特征继承(或者说实施)您的命令?

Trait CancelComponentCommand {
    String cancelUrl

    static constraints = {
        cancelUrl validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
    }
}

Trait RedirectComponenCommand {
    String redirectUrl

    static constraints = {
            redirectUrl validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
    }
}

@Validateable
class MyCommand implements CancelComponentCommand, RedirectComponenCommand {

}

PS不需要设置nullable: false,默认为false。此外,如果使用驼峰命名法编写字段,代码的可读性会更高。