grails - 注册多个属性编辑器

标签 grails

我在注册自定义属性编辑器时遇到问题。我这样注册:

class BooleanEditorRegistrar implements PropertyEditorRegistrar {

   public void registerCustomEditors(PropertyEditorRegistry registry) {
      registry.registerCustomEditor(Boolean.class,
         new CustomBooleanEditor(CustomBooleanEditor.VALUE_YES, CustomBooleanEditor.VALUE_NO, false))
      registry.registerCustomEditor(Boolean.class,
         new CustomBooleanEditor(CustomBooleanEditor.VALUE_ON, CustomBooleanEditor.VALUE_OFF, true))
   }
}

但只有第一个被应用。是否可以注册多个?

最佳答案

每个类只能设置一个属性编辑器。如果您使用的是Spring的CustomBooleanEditor ,您可以将默认值(“true”/“on”/“yes”/“1”、“false”/“off”/“no”/“0”)与单参数构造函数一起使用,或者完全使用true 和 false 各用一个字符串。如果您需要更灵活的东西,则必须实现自己的属性编辑器。例如:

import org.springframework.beans.propertyeditors.CustomBooleanEditor

class MyBooleanEditor extends CustomBooleanEditor {

    def strings = [
        (VALUE_YES): true, 
        (VALUE_ON): true,
        (VALUE_NO): false,
        (VALUE_OFF): false
    ]

    MyBooleanEditor() {
        super(false)
    }

    void setAsText(String text) {
        def val = strings[text.toLowerCase()]
        if (val != null) {
            setValue(val)
        } else {
            throw new IllegalArgumentException("Invalid boolean value [" + text + "]")
        }
    }
}

关于grails - 注册多个属性编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266050/

相关文章:

grails - Grails将2.4.4升级到3.2.8,JavaScript和CSS源产生空白,spring-security-shiro/core

hibernate - 不要更新或删除数据库中的数据

spring - 如何将 session ID保存到我的persistenceLogin表中

java - Spring Security ACL继承: How does it really works?

grails - 一对多(或一个)级联创建 View

grails - 带投影的 CreateCriteria 不会选择所有列

caching - grails中springcache插件的使用

javascript - 通过javascript为taglib设置属性

grails - 为什么在插件的配置中未定义Config.groovy变量?

grails - 合成未创建外键引用