Creating Custom Property Editors

Problem

In addition to registering the built-in property editors, you may want to write your own custom property editors for converting your custom data types.

Solution

You can write custom property editors by implementing the java.beans.PropertyEditor interface or extending the convenient support class java.beans.PropertyEditorSupport.

How It Works

For example, let’s write a property editor for the Product class. You can design the string representation of a product as three parts, which are the concrete class name, the product name, and the price. Each part is separated by a comma. Then you can write the following ProductEditor class for converting them:

package com.shop;
import java.beans.PropertyEditorSupport;
public class ProductEditor extends PropertyEditorSupport {
public String getAsText() {
Product product = (Product) getValue();
return product.getClass().getName() + "," + product.getName() + "," + product.getPrice();
}
public void setAsText(String text) throws IllegalArgumentException {
String[] parts = text.split(",");
try {
Product product = (Product) Class.forName(parts[0]).newInstance();
product.setName(parts[1]);
product.setPrice(Double.parseDouble(parts[2]));
setValue(product);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}

The getAsText() method converts a property into a string value, while the setAsText() method converts a string back into a property. The property value is retrieved and set by calling the getValue() and setValue() methods. Next you have to register your custom editor in a CustomEditorConfigurer instance before it can be used. Registration is the same as for the built-in editors. Now you can specify a product in text format for any property whose type is Product.

<beans …>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.shop.Product">
<bean class="com.shop.ProductEditor" />
</entry>
</map>
</property>
</bean>
<bean id="productRanking"
class="com.shop.ProductRanking">
<property name="bestSeller">
<value>com.shop.Disc,CD-RW,1.5</value>
</property>
</bean>
</beans>

In fact, the JavaBeans API will automatically search a property editor for a class. For a property editor to be searched correctly, it must be located in the same package as the target class, and the name must be the target class name with Editor as its suffix. If your property editor is provided in this convention, such as in the preceding ProductEditor, there’s no need to register it again in the Spring IoC container.