Spring Conversion Service Usage For Converters

28-01-2015

In some cases we need to use Converter:

Case 1: To help simplifying bean configurations, Spring supports conversion of property values to and from text values.
Case 2: In a form, sometimes it is necessary to convert a text value to specific object, For example in a combo box there are multiple String values stored. Each value can be converted to related objects.

There are three steps to create Converter:

1. Create Converter class
2. Create conversion service bean in the spring config file then register the converter class
3. Refer to this bean from conversion-service attribute of the <mvc:annotation-driven>


Create Converter Class
public class AdminRoleConverter implements Converter<String,AdminRole> {
    @Autowired
    private AdminRoleService adminRoleService;
    @Override
    public AdminRole convert(String id) {
        return adminRoleService.get(Integer.valueOf(id));
    }
}


Conversion Service Bean
<bean id="conversionService"
          class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.java.spring.mvc.converter.AdminRoleConverter"/>
            </list>
        </property>
    </bean>


Refer from <mvc:annotation-driven>
 <mvc:annotation-driven conversion-service="conversionService"/>

After these three steps, you can successfully use in a jsp form:
<form:select id="slcRole" path="adminRole">
    <form:option label="SELECT" value="${null}"/>
    <form:options items="${roles}" itemValue="adminRoleId" itemLabel="role" />
</form:select>

Note: adminRole is a AdminRole object and option items consists of multiple AdminRole objects, but displayed values are text values. Because of this, we need to convert text values to AdminRole objects. Therefore, Spring conversion service is used in such operations.

© 2019 All rights reserved. Codesenior.COM