Monday, September 6, 2010

Conversion from/to between String and non String properties

Spring Custom Property Editors:

We might be wondering that even though the property of a bean if of any type (int, URL, Date etc), we always set the properties in the context file using the property attribute or constructor inside double quotes (" ") i.e. we always set the properties as String.
For example, if there is an age property of an employee and the property is of type int, then too, in the context file, the property for the employee bean is set as following:

<bean id="emp" class="com.blog.examples.employee">
<property name="age" value="25" />
</bean>


So, we see that the property is set within double quotes i.e. String. Similarly, consider this property wsdlDocumentUrl which we use for JaxRpcPortProxyFactoryBean for wiring Web Services:

<property name="wsdlDocumentUrl" value="http://www.mycompany.com/CustomService?wsdl" />


Though the wsdlDocumentUrl accepts a property of java.net.URL type, it is still specified with the String convention inside the context file. The Question is how does the property mapping happens from String to non-String specific types?

Well, under the covers, Spring automatically converts String value to the Specific type based on the Actual property type of the bean and this conversion happens through a feature of JavaBeans API known as PropertyEditor.
The java.beans.PropertyEditor interface provides a means to customize how String values are mapped to non-String types. A convinent implementation of this interface- java.beans.PropertyEditorSupport has 2 methods of interest to us:
1. getAsText() returns the String representation of a property's value
2 setAsText(String value) sets a bean property value from the String value passed in

If an attempt is made to set a non-String property to a String value, the setAsText() method is called to perform the conversion and Likewise, the getAsText() method will be called to to return a textual representation of the property's value.

Similarly, here are the Several PropertyEdiotors that Spring uses internally to convert the value of a property from a String to non-Strng specific type.
ClassEditor, CustomDateEditor, FileEditor, LocaleEditor, URLEditor etc

No comments:

Post a Comment