2

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

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))
   }
}

但唯一的第一个被应用。可以注册多个吗?

4

1 回答 1

2

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

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 + "]")
        }
    }
}
于 2012-09-04T16:59:38.483 回答