Grails命令扩展了另一个命令bug

时间:2013-05-23 20:48:47

标签: java oop grails command extend

当我扩展一个通用命令以重用它的自定义验证器时,我在Grails中的命令出现问题。

当我清理grails项目时,它会丢失对扩展自定义验证程序的引用。我需要在项目运行时在CommandA中导致语法错误并撤消该错误,以便它编译回命令。

file:/src/groovy/app/commands/ImageCommand.groovy

class ImageCommand {
    static imageValidator = { value, command ->
        ... DO SOMETHING ...
    }
}

file:/src/groovy/app/commands/CommandA.groovy

class CommandA extends ImageCommand {
    def file
    static constraints = {
        file nullable: true, blank: true, validator: imageValidator
    }
}

导致错误我只是删除了CommandA的一部分:

class CommandA extends ImageCommand {
    def file
    static constraints = {
        file nullable: true, blank: 
    }
}

撤消它以强制重新编译:

class CommandA extends ImageCommand {
    def file
    static constraints = {
        file nullable: true, blank: true, validator: imageValidator
    }
}

我该怎么办?我无法将CommandA移动到Controller文件中,因为我在许多地方使用它。

*使用Grails 2.2.2

1 个答案:

答案 0 :(得分:0)

您可以尝试将验证程序移动到src\groovy中的单独类,如下所示:

class PhoneNumberConstraint extends AbstractConstraint {
    private static final String NAME = "phoneNumber";
    private static final String DEFAULT_MESSAGE_CODE = "default.phoneNumber.invalid.message";

    @Override
    protected void processValidate(Object target, Object propertyValue, Errors errors) {
        if (!isPhoneNumber(target, propertyValue)) {
            Object[] args = [constraintPropertyName, constraintOwningClass, propertyValue]
            rejectValue(target, errors, DEFAULT_MESSAGE_CODE, DEFAULT_MESSAGE_CODE, args);
        }
    }

    private boolean isPhoneNumber(Object target, Object propertyValue) {
        if(propertyValue instanceof String && ((String)propertyValue).isNumber() &&
                (((String)propertyValue).length() == 13 || ((String)propertyValue).length() == 11)) {
            return true
        }
        return false
    }


    @Override
    boolean supports(Class type) {
        return type != null && String.class.isAssignableFrom(type)
    }

    @Override
    String getName() {
        return NAME
    }
}

然后在resources.groovy注册验证器,如下所示:

beans = {
    ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.NAME, PhoneNumberConstraint.class);
}

通过命令完美地为我服务。