javaspringspring-mvcpropertyeditor

Spring mvc register custom PropertyEditor


Let's say we have:

class Car:

public class Car{
   private String model;
   private String brand;
   private Collection<People> owners;

   //constructor,getters and setters
}

Class People:

public class People{
   private Car car;
   private String name;
   private Gender gender;

   //constructor,getters and setters
}

Class Gender:

public class Gender{
   private Char gender;

   //constructor,getters and setters
}

Then if i want to pass the collection owners to my view:

<body>
        <h1>Car detail: </h1>
        <h2>Owners: </h2>
        <table>
            <form:form modelAttribute="owners" method="post" action="processOwnersSelection.htm">
                <tr>
                    <td>
                        <ul>
                            <form:checkboxes element="li" path="owners" items="${owners}"></form:checkboxes>
                        </ul>
                    </td>
                </tr>
                <tr>
                    <td>
                        <button type="submit">Next</button>
                    </td>
                </tr>
            </form:form>
        </table>               
    </body>

By my Controller:

@RequestMapping(value = "/selectOwners")
    protected ModelAndView showOwnersSelection() throws ServiceException{
        return new ModelAndView("car/ownerSelection", "owners", super.getService().getAllOwners());
    }

Note. This will be used to connect multiple owners (who existe in out DB) to a car.

i'll get an error:

org.springframework.beans.NotReadablePropertyException: Invalid property 'owners' of bean class [java.util.HashMap$Values]: Bean property 'owners' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?


As far as I understand Spring converts these by using implamentations of PropertyEditor or Converter ?

So I should manually write one, but then how will Spring know i made one he(or she) has to use ? And how should one look like ?


Solution

  • Spring 3 Type Converter SPI supercedes JavaBean PropertyEditors.

    <mvc:annotation-driven /> in the configuration file will automatically install default type converters. We can override defaults with annotations such as @DateTimeFormat or @NumberFormat.

    For custom field types, we can follow below convention over configuration:

    1. Define a static valueOf(String) method or Constructor(String) to parse your value from its String representation

    2. Implement toString() to print your value for display

    See this link for more details.