【问题标题】:Spring/Grails custom property editors for a specific property of the class用于类的特定属性的 Spring/Grails 自定义属性编辑器
【发布时间】:2012-12-12 09:33:40
【问题描述】:

我想为域类的属性之一注册一个自定义属性编辑器,类是这样的

class Accessory{
  String name
  byte[] image
}

从客户端我正在为图像发送一个 base64 编码的字符串,现在我希望这个字符串在绑定时自动转换为字节数组

我的属性编辑器类看起来像这样

import java.beans.PropertyEditorSupport
import org.apache.commons.codec.binary.Base64
class CustomAccessoryImageEditor extends PropertyEditorSupport{


    String getAsText() {
        value.toString()
    }

    void setAsText(String text) {
        String encodedImage = text?:""
        byte[] imageBytes = decodeImageToBytes(encodedImage)
        if(imageBytes.size()){
            value = imageBytes
        }


    }

    byte[] decodeImageToBytes(String encodedImage){
            return Base64.decodeBase64(encodedImage)
        }
}

我无法找到正确注册此编辑器的方法。

现在我的注册员班里有这样的东西

registry.registerCustomEditor(byte, Accessory.image, new CustomAccessoryImageEditor())

但是当我运行它时,我收到一条错误消息,提示找不到类附件上的属性图像

我有两个问题, 1. 是否可以为类的特定属性提供属性编辑器? 2.如果是,那么如何指定属性路径?

【问题讨论】:

  • registerCustomEditor(byte[], 'image', new Custom....) 应该为 byte[] 类型的所有名为 image 的属性注册一个编辑器,但我不确定有什么方法可以将其限制为一个特定的类。
  • 是的,我知道,实际上它没有考虑属性路径 - 'image',虽然绑定它说找不到类 CustomAccessoryImageEditor 上的属性图像。如果我可以将其限制为名称为 image 的属性会很好

标签: spring grails path editor custom-properties


【解决方案1】:

我认为不可能为类的特定属性提供属性编辑器。但是如果 image 属性是 Image 类型(byte[] 的包装器),那么您可以为此注册一个编辑器,Spring 会将编码的文本表示绑定到自定义包装器。

【讨论】:

  • 感谢您回复戴夫,是否有任何解决方法可以实现此目的?我不能有一个包装器,也想知道这个数据绑定是否有更详细的文档,springsource的文档还不够
  • PropertyEditor 是一个标准的 JDK 特性,所以 Spring 没有记录它。不过在 Spring 中还有其他选择(参见第 6 章或用户指南static.springsource.org/spring/docs/current/…)。您可能可以使用 Converter for String to byte[] - 那么问题将是在您的用例中是否可以将其注入正确的位置。我们对您的应用程序知之甚少(我对 Grails 也知之甚少),无法为您提供更多指点。
猜你喜欢
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多