2012-09-04 38 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

它的工作原理,謝謝。 –