我在注册自定义属性编辑器时遇到问题。我这样注册:
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/