2012-09-04 45 views
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)) 
    } 
} 

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

回答

2

您只能为每个类设置一个属性编辑器。如果您使用Spring的CustomBooleanEditor,您可以使用默认值(“true”/“on”/“yes”/“1”,“false”/“off”/“no”/“0”) -arg构造函数,或者正好一个字符串,分别表示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 + "]") 
     } 
    } 
} 
+0

它的工作原理,谢谢。 –