Search code examples
springgrailspatheditorcustom-properties

Spring/Grails custom property editors for a specific property of the class


I want to register a custom property editor for one of the properties of a domain class, the class is something like this

class Accessory{
  String name
  byte[] image
}

From the client side i am sending a base64 encoded string for the image, now i want this string to automatically convert to byte array at the time of binding

My property editor class looks like this

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

I am not able to find a way to register this editor properly.

Right now i have something like this in my registrar class

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

but when i run this, i get an error message saying cannot find property image on class Accessory

I have two questions, 1. Is it possible to have a property editor for a specific property of a class ? 2. If yes then how to specify the property path ?


Solution

  • I don't think it is possible to have a property editor for a specific property of a class. But if the image property was of type Image (a wrapper for byte[]) then you could register an editor for that and Spring would bind an encoded text representation to the custom wrapper.